这个c ++代码有什么问题可以找到低于1000的5和3的所有倍数的总和?

0 c++ for-loop if-statement floor

我非常中级.我知道有更快的方法来解决这个项目欧拉问题,但这是我提出的方式,它应该仍然有效,对吧?我知道这个问题不是很具体,但我发现很难解决一个我不知道的问题.任何帮助表示赞赏:(

#include <iostream>
#include <math.h>                           //declare floor
using namespace std;


int main()
{
    cout << "What number would you like to find the sum of all multiples of 5 and 3?"<<endl;
    int n;
    int sum = 0;
    cin >> n;
    for(int x = 1; x < n; x = x + 1){
           float f = x/5;                   //divides every number from 0 to n-1 (intended to be 1000) by 5.
           float t = x/3;
           if(floor(f) == f){               //checks to see if it is a whole number by rounding the answer, and seeing if that equals the original. If it does, it is truly a whole number answer.
                sum = sum + x;              //since it is divisible by 5, the number is added to the sum.
           }else{                           //this is ELSE so that same multiples aren't counted twice. if x is not multiple of 5, check to see if it's a multiple of 3. if none, nothing happens
                 if (floor(t) == t){
                    sum = sum + x;
                }
           }
    }
    cout << "Sum of all multiples is " << sum << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Chr*_*tos 6

双方x5在下面的语句整数.

float f = x/5; 
Run Code Online (Sandbox Code Playgroud)

所以结果总是等于除法的商.

您应该将代码更改为以下内容:

float f = x/5.f; 
Run Code Online (Sandbox Code Playgroud)

如果你想获得浮动结果.

但是,这不会解决您的问题,可以解决这个问题,如下所示:

for(int x = 1; x < n; x = x + 1){
    if(x%5== 0 || x%3 == 0){
        sum = sum + x;
    }
}
Run Code Online (Sandbox Code Playgroud)

%是取模运算,给你一个部门的betwene两个整数的余数.有关详细信息,请查看此处.