gpt4 book ai didi

c++ - 程序保持垃圾邮件数量?

转载 作者:行者123 更新时间:2023-12-02 10:00:32 26 4
gpt4 key购买 nike

#include <iostream>
using namespace std;
int main(){
int a;
int b;
int dif;
cout<<"insert a: "<<endl;
cin>>a;
cout<<"insert b: "<<endl;
cin>>b;
if(a>b){
while(dif>=3){
dif=a-b;
cout<<dif;
}
}else{
while(dif>=3){
dif=b-a;
cout<<dif;
}
}
}
这应该是一个程序,它读取两个数字,并不断从较大的数字中减去较小的数字,直到差值小于3个单位。在执行此操作时,它还应该在每次迭代时输出差异,并且由于某种原因,它会散布差异或不输出任何内容。救命?

最佳答案

while循环中的两个问题:

while(dif>=3){
dif=a-b;
cout<<dif;
}
首先, dif未初始化使用,使用它会导致未定义的行为。修复该问题后,循环仍无法执行您想要的操作。 dif=a-b;将在每次迭代中为 dif分配相同的值,因此循环将永远不会运行(条件是循环之前的 false),一次(条件是分配之后的 false)或永远(条件仍然是分配之后的 true)运行。我想这不是预期的行为。

...and keeps subtracting the smaller one from the bigger one until the difference is < 3 units.


您实际上忘记了从另一个数中减去一个数。那将是(如果 a更大):
while ( a-b >= 3) a -= b;
或带有其他变量(我认为这没有帮助,但会增加复杂性):
int diff = a-b;
while (diff >= 3) {
a -= b;
diff = a-b;
}

关于c++ - 程序保持垃圾邮件数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62716300/

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