用c++编写的暴力搜索程序
brute-force search program with C++
我是c++新手。最近我正在浏览谷歌开发者的教程:https://developers.google.com/edu/c++/getting-started
这是一个简单的匹配谜题,使用暴力搜索解决方案:马的价格是10美元,猪是3美元,兔子只有0.5美元。一个农民花100美元买了100只动物,每种动物他买了多少只?
下面是我的代码:#include <iostream>
using namespace std;
int main() {
int pHorse = 10;
int pPig = 3;
int pRabbit = 0.5;
for (int i = 0; i <= 100 / pHorse; ++i) {
for (int j = 0; j <= ((100 - i * pHorse) / pPig); ++j) {
int money = (100 - pHorse * i - pPig * j);
if (pRabbit * (100 - i - j) == money) {
cout << "The number of Horses are: " << i << endl;
cout << "The number of Pigs are: " << j << endl;
cout << "The number of Rabbits are: " << 100 - i - j << endl;
}
}
}
return 0;
}
然而,它给出了像[10 0 90]这样荒谬的答案,这显然是不正确的。
我不知道问题出在哪里。任何想法?代替
int pRabbit = 0.5;
试
double pRabbit = 0.5;
int不能容纳0.5。
0.5不是整数。它是一个浮点数,因此不能将0.5存储在整数变量中。您可以使用double
或float
变量。
:
double pRabbit = 0.5;
或
float pRabbit = 0.5;
相关文章:
- 我的二进制搜索程序只是关闭了
- 返回不需要的值的二叉搜索程序
- 为什么当我尝试搜索双链表中第一个数据条目之外的数据时,程序崩溃了?
- 将数据从C++程序发布到弹性搜索
- 我正在尝试使用 c++ 编写二叉搜索树,但该程序仅接受 2 个输入并停止
- 二进制搜索树操作程序错误:分割故障(核心倾倒)
- 如何使该程序在数组中打印搜索字符的索引,否则将找不到它
- 搜索功能使程序崩溃
- 二叉搜索树程序说根不命名类型
- 是否可以显示需要线性搜索的时间才能找到您在程序中找到的密钥
- 运行 c++ 程序时搜索的路径错误
- 需要程序来搜索整个文本文件
- 程序设置二叉树,打印和搜索 - 节点类C++
- 二进制搜索程序。在应用测试用例时给出正确的输出仍然显示" "超出时间限制" "错误
- 查找符号时,程序不会从正确的库中搜索
- 将我的二叉搜索程序改进为递归程序
- 二进制搜索程序无法识别边界?
- C++,A* 搜索程序无法正确计算到出口的距离
- 用于特定网站的浏览器搜索程序
- 用c++编写的暴力搜索程序