C++中的多个if语句

Dav*_*081 4 c++ if-statement

我正在做第一个项目欧拉问题,我刚刚做了这个

#include <iostream>
using namespace std;

int main(){

int threes =0;
int fives = 0;
int both = 0;
for (int i = 0; i < 10; i++){

       if(i%3==0){
   threes += i;
   }

       if(i%5==0){
   fives += i;
   }

      if ( i % 5 == 0 && i % 3 == 0){
      both += i;
  }

}

cout << "threes = " << threes << endl;
cout << "fives = " << fives << endl;
cout << "both = " << both << endl;

cout << " threes + fives - both = " << endl;
int result = (threes + fives) - both;
cout << result<< endl;

return 0;
}
Run Code Online (Sandbox Code Playgroud)

我的教授最近在一个不同的问题上纠正了我这样做,说了一些关于其他陈述的事情,但我不明白为什么我必须在下一个前面加上其他的if.为了它的价值我还有另一个版本if else(i%5){fives + = ....}并且他们都工作并得到我正确的答案.

我的问题是这种思维方式本质上是错误的,是风格还是我没有逻辑地思考某些事情?

如果它有效,为什么要使用switch语句呢?

小智 5

我唯一看到你的实现错误的是,在数字是3的倍数和5的倍数的情况下,不仅两个变量都增加了,而且五个和三个变量也增加了.基于教授所描述的内容,我相信他希望你使用else - 如果是这样,当你传入一个3的倍数和5的倍数的数字时,这两个变量是唯一增加的变量.

你在两种方式中得到正确答案的原因是因为你只是在for循环中达到10,如果你把它增加到i <= 15,你会得到五分之三和三分之一比我想象的要高.

例如:

for( int i = 0; i < 10; i++ )
{
   if( ( ( i % 3 ) == 0 ) && ( ( i % 5 ) == 0 ) )
   {
      both++;
   }
   else if( ( i % 3 ) == 0 )
   {
      threes++;
   }
   else if( ( i % 5 ) == 0 )
   {
      fives++;
   }
}
Run Code Online (Sandbox Code Playgroud)