【发布时间】:2016-11-11 20:41:05
【问题描述】:
我很中级。我知道有更快的方法来解决这个 Project Euler 问题,但这是我想出的方法,它应该仍然有效,对吧?我知道这个问题不是很具体,但我发现很难用谷歌搜索一个我不知道的问题。任何帮助表示赞赏:(
#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;
}
【问题讨论】:
-
对于这个问题不要使用浮点数(或双精度)。
-
正如@RichardCritten 所说,您不需要使用这些数据类型。我建议使用
%运算符。 -
其实这最好描述为初级问题
-
一个非常初级的问题。
标签: c++ if-statement for-loop floor