我需要比较五个整数并找到最大和最小的整数.我需要通过仅使用if和else语句来解决它,我不能使用找到max,min输入的数组或特定函数.
这是我到目前为止所做的:
int n1, n2, n3, n4, n5, biggest,smallest;
n1=biggest;
cout << "Enter the five numbers: ";
cin >> n1 >> n2 >> n3 >> n4 >> n5 ;
if ((n2>=n1) && (n2>=n3) && (n2>=n4) && (n2>=n5)) {
n2 = biggest;
}
else if ((n3>=n4) && (n3>=n5)) {
n3 = biggest ;
}
else if (n4>=n5) {
n4 = biggest ;
}
else {
n5 = biggest ;
}
cout << biggest ;
Run Code Online (Sandbox Code Playgroud)
为什么输出0而不是最大数?
试试这个 :
int main ()
{
int n1, n2, n3, n4, n5, biggest,smallest;
cout << "Enter the five numbers: ";
cin >> n1 >> n2 >> n3 >> n4 >> n5 ;
smallest=biggest=n1;
if(n2>biggest){
biggest=n2;
}
if(n2<smallest){
smallest=n2;
}
if(n3>biggest){
biggest=n3;
}
if(n3<smallest){
smallest=n3;
}
if(n4>biggest){
biggest=n4;
}
if(n4<smallest){
smallest=n4;
}
if(n5>biggest){
biggest=n5;
}
if(n5<smallest){
smallest=n5;
}
cout<<smallest<<"\t"<<biggest;
return 0;
}
Run Code Online (Sandbox Code Playgroud)