저는 매우 중급입니다. 이 프로젝트 오일러 문제를 해결하는 훨씬 더 빠른 방법이 있다는 것을 알고 있습니다. 그러나 이것이 내가 생각해 냈던 방식이었고 계속 작동해야했습니다. 맞습니까? 나는이 질문이 매우 구체적이지는 않다는 것을 알고 있지만 Google에 알기 힘든 문제가 있음을 알고 있습니다. 어떤 도움을 주시면 감사 :(1000 이하의 5와 3의 모든 배수의 합계를 찾으려면이 C++ 코드에 어떤 문제가 있습니까?
#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;
}
이 문제에 대해서는 float (또는 double)을 사용하지 마십시오. –
@RichardCritten은 이러한 데이터 유형을 사용할 필요가 없다고 말했습니다. '%'연산자를 사용하는 것이 좋습니다. – Gavin
실제로 이것은 중급 문제로 가장 잘 묘사됩니다. –