gpt4 book ai didi

c++ - C++中的多个if语句

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:16:07 27 4
gpt4 key购买 nike

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

#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;
}

我的教授最近纠正了我在另一个问题中这样做的问题,他说了一些关于 else 语句的内容,但我不明白为什么我必须在下一个 if 前面添加 else。对于它的值(value),我有另一个版本 else if(i%5){ fives += .... }他们都工作并为我提供了正确的答案。

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

如果可行,为什么还要使用 switch 语句?

最佳答案

我在您的实现中看到的唯一错误是,在数字既是 3 的倍数又是 5 的倍数的情况下,不仅两个变量都递增,而且五个和三个变量也递增。根据教授的描述,我相信他希望你使用 else-if,这样当你传入既是 3 的倍数又是 5 的倍数的数字时,both 变量是唯一递增的变量。

你得到两种方式都正确答案的原因是因为你在 for 循环中只会得到 10,如果你将它增加到 i <= 15 你会得到比我认为他预期的高 1 的五和三。

例如:

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++;
}
}

关于c++ - C++中的多个if语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6241672/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com