gpt4 book ai didi

c++ Sentinel循环,存储最小和最大数字

转载 作者:行者123 更新时间:2023-11-30 02:16:09 25 4
gpt4 key购买 nike

这是我的程序:

#include <iostream>
using namespace std;

int main(){
int num;
int numtotal = 0;
int numcount = 0;
int big = 0;
int low = 0;

cout<<"enter number or 0 to exit"<<endl;
cin>>num;
while(num != 0){
numtotal = numtotal + num;
numcount++;
big = num;
low = num;

cout<<"enter number or 0 to extit"<<endl;
cin>>num;

if(num < low){
low = num;
}
else if(num > big){
big = num;
}
}

cout<<"total of numbers: "<<numtotal<<endl;
cout<<"totoal of numbers entered: "<<numcount<<endl;
cout<<"biggest number: "<<big<<endl;
cout<<"lowest number: "<<low<<endl;
}

“低”和“大”输出始终是用户输入的最后两个数字,例如:

( 5, 4, 3, 2)

最大的数字:2

最小数字:0

我做错了什么?谢谢

最佳答案

如果用户在 while 循环中输入 0,则不需要将 biglow 设置为 num以达到您想要的结果。

否则,如果您不这样做,在用户仅输入正数的情况下,您的输出最小数字将始终为 0,我认为您不希望这样:

#include <iostream>
using namespace std;

int main() {
int num;
int total = 0;
int count = 0;

cout << "Enter number or 0 to exit" << endl;
cin >> num;

int biggest = num;
int lowest = num;

while (num != 0) {
total += num;
count++;
cout << "Enter number or 0 to exit" << endl;
cin >> num;
if (num != 0) {
if (num < lowest) {
lowest = num;
} else if (num > biggest) {
biggest = num;
}
}
}

cout << "Total of numbers: " << total << endl;
cout << "Amount of numbers entered: " << count << endl;
cout << "Biggest number: " << biggest << endl;
cout << "Lowest number: " << lowest << endl;

return 0;
}

示例用法:

Enter number or 0 to exit
5
Enter number or 0 to exit
4
Enter number or 0 to exit
3
Enter number or 0 to exit
2
Enter number or 0 to exit
0
Total of numbers: 14
Amount of numbers entered: 4
Biggest number: 5
Lowest number: 2

关于c++ Sentinel循环,存储最小和最大数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55269867/

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