用c++编写的暴力搜索程序

brute-force search program with C++

本文关键字:搜索 程序 c++      更新时间:2023-10-16

我是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存储在整数变量中。您可以使用doublefloat变量。

:

double pRabbit = 0.5;

float pRabbit = 0.5;