没有从非常简单的功能得到正确的答案

时间:2013-10-20 19:45:56

标签: c++

好的,所以我是一个完整的菜鸟。我正在尝试使用Project Euler来更好地学习C ++。我正在做问题#1,但我没有得到正确的输出。当我运行它时,我得到numTotalThree为-3,numTotalFive为-5,而numTotal为0.我的函数有问题,但我不确定我做错了什么。我该如何解决这个问题?

#include <iostream>
using namespace std;

int main()
{
    int amount = 1000;
    int numOfThree = amount / 3;
    int numOfFive = amount / 5;
    int numTotalThree = 0;
    int numTotalFive = 0;
    int numTotal = numTotalThree + numTotalFive;

    cout << numOfThree << endl;
    cout << numOfFive << endl;

    for(int i = 0; i <= numOfThree; i++)
    {
        numTotalThree += numTotalThree + 3;
    }

    cout << numTotalThree << endl;

    for(int i = 0; i <= numOfFive; i++)
    {
        numTotalFive += numTotalFive + 5;
    }

    cout << numTotalFive << endl;

    cout << numTotal << endl;

    system("PAUSE");
    return 0;
}

4 个答案:

答案 0 :(得分:3)

我猜你需要这样的东西:

int sum = 0;

for (int i =0; i < 1000; ++i){
    if(i % 3 == 0 || i % 5 == 0){
        sum += i;
    }
}

稍后编辑:我不知道你为什么要计算3或5小于1000的可分数。问题(项目欧拉 - 问题1)要求所有小于1000的数字之和,可以用3或5整除。

答案 1 :(得分:0)

C ++不是一种程序性的功能语言 - 这意味着你必须按顺序做事。当你这样做时:

int numTotalFive = 0;
int numTotal = numTotalThree + numTotalFive;

当更新numTotalThree和numTotalFive时,它将被执行,而不是再次执行。如果您不再触摸它,那将是输出的值。

答案 2 :(得分:0)

接下来是个想法:

通过检查余数%== 0,检查有多少可被3整除。五个人一样,然后两个人一样。从前两个的总数中减去可被两者整除的数字,以得到准确的答案。

int divisibleByThree=0; 
int divisibleByFive=0;
int divisibleByBoth=0;
int total;

for(int i=0; i<1000; i++)
{
    if (i%3==0)
        divisibleByThree++;
    if (i%5==0)
        divisibleByFive++;
    if (i%5==0) && i%5==0)
        divisibleByBoth++;
}

    total = divisibleByThree + divisibleByFive - divisibleByBoth;
    return total;

答案 3 :(得分:0)

numTotalThree在{0,333]

中溢出n
  • 3/2 *( - 2 + 2 n

{0,200]

中的numTotalFive同样n
  • 5/2 *( - 2 + 2 n

所以你看到负值。

正如其他人所说,你可能需要重温你的逻辑。

您只需要总结[0,1000]中可被3或5整除的数字

size_t total =0;
for (size_t x =0; x < 1000; x++){
    if( (x % 3 == 0) || (x % 5 == 0) ){
        total += x;
    }
}