我正在编写一个程序,让用户输入一个数字列表,看看他们输入的最大和最小数字是多少。用户可以输入的数字量仅为2(无论他们需要多少,直到他们输入-99标记列表的结尾)。我不确定如何在输入-99之前重复输入数字的过程。如果有人可以提供帮助,那将非常感激。 (正如提醒一样,-99不应该是列表的一部分,它应该在-99之前找到所有数字中最小和最大的数字)。我只能使用循环来解决这个问题。
int main(){
int firstNumber = 0;
int nextNumber = 0;
int greatestNumber = 0;
while (firstNumber != -99 || nextNumber != -99){
cin >> firstNumber;
if (firstNumber == -99){
cout << "No numbers were entered." << endl;
break;
}
greatestNumber = firstNumber;
cin >> nextNumber;
if (nextNumber == -99){
cout << "the greatest number is " << firstNumber << endl;
cout << "the smallest number is " << firstNumber << endl;
break;
}
if (nextNumber > greatestNumber){
greatestNumber = nextNumber;
cout << "the greatest number is " << greatestNumber << endl;
cout << "the smallest number is " << firstNumber << endl;
} else {
cout << "the greatest number is " << greatestNumber << endl;
cout << "the smallest number is " << nextNumber << endl;
}
}
system("pause");
return 0;
}
答案 0 :(得分:0)
您只有firstNumber
而不是secondNumber
和currentNumber
。如果它大于greatestNumber
,则将其分配给greatestNumber
。然后循环获取新的currentNumber
并再次检查。
当用户结束时(可能以比用户输入-99
更多的方式发生),您结束循环并打印最大数字。
哦,我建议您将greatestNumber
初始化为零以外的其他内容,至少如果您希望用户能够输入负数(但大于-99
)。
对于最小的数字,有一个等价变量smallestNumber
,你初始化为一个非常大的值(如std::numeric_limits<int>::max()
)并进行等式检查(但是少于 - 而不是更大 - 比)。
一些伪代码:
int smallest = REALLY_BIG_NUMBER;
int largest = REALLY_SMALL_NUMBER;
int current;
loop while there is input to put in current
{
if current is your exit condition then exit loop
if current is larger than largest the reassign largest
if current is smaller than smallest then reassign smallest
}
print largest and smallest