[英]Using loop asked user to input numbers
我用很多不同的方法嘗試過,但仍然不起作用
#include<iostream>
using namespace std;
int main(){
float i=1,no,max=0,min=no;
while(i>0){
cout<<"Enter a number:";
cin>>no;
if(no!=0) {
if(no>max){
max=no;
}
if(no<min){
min=no;
}
}
if(no==0){
cout<<"max:"<<max<<endl;
cout<<"min:"<<min<<endl;
return 0;
}
}
}
首先在這里:
float i = 1, no, max = 0, min = no;
no
在您開始使用時未初始化。 行為未定義。
其次,您的while
循環是一個無限循環,因為您永遠不會更改i
的值或使用break
。
建議:
0
初始化是不行的,但我不會破壞你的練習double
代替float
#include <iostream>
using namespace std;
int main(){
cout<< "Enter a number- Enter 0 to see result: ";
int num = 0, max = 0, min=0;
for( int i = 1; i <= 100; ++i){
cin>> num;
if(i==1){
max=num;
min=num;
}
else{
if( num > max )
max = num;
else if( num == 0 )
break;
else if( num < min )
min = num;
}
}
cout<<"min:"<< min <<" max:"<< max;
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.