【发布时间】:2017-01-19 05:29:19
【问题描述】:
我正在为一项任务编写代码,该程序希望我编写一个程序,询问用户他们想要输入的整数数量,然后它接受每个输入,同时测试该值是最大值还是最小值。除了 1 之外,我的程序对于输入的每个整数都运行良好。当我输入 int 1 时,仅记录最大值,即使输入的数字在技术上也是最小值,这是由于 if 语句导致循环在找到后重复如果数字是最大值或最小值,则输出,在这种情况下,数字将始终为最大值,因此测试永远不会再次运行。我怎样才能解决这个问题?
#include <iostream>
using namespace std;
int main()
{
int input;
int tmp;
int counter = 1;
int max_num=0;
int min_num;
//prompt user for integer amount
cout << "How many integers would you like to enter? " << endl;
cin >> input;
cout<< "Please enter " << input << " integers." << endl;
tmp = input;
//loop for requested amount with a test for each input
while (counter <= tmp){
cin >> input;
//if smaller than previous number it is the minimum
if (input < min_num){
min_num = input;
counter++;
}
// if larger than previous number it becomes max number
else if (input > max_num){
max_num = input;
counter++;
}
//continue loop if number isn't bigger than max or smaller than min
else {
counter++;
}
}
//display the max and min
cout << "min: "<< min_num << endl;
cout << "max: " << max_num<< endl;;
return 0;
}
【问题讨论】:
-
我可以通过将 if 语句嵌套在 min 语句下的 max number 来解决这个问题。但似乎应该有更好的解决方案?
-
一个提示:当语句必须在每个循环中执行而不考虑条件时,不要将它放在条件中。我说的是
counter++。您应该将该语句放在循环的末尾。它将减少代码重复并使您的代码更具可读性和更小。 -
@JosephL.甚至更好:将语句放在循环的开头:
for( int counter = 1; i <= tmp; ++ counter) {...}.` -
谢谢你们,在我的 linux 服务器上测试这个程序时,我遇到了同样的问题,即使它似乎在我的 windows 机器上修复了?