2017-06-16 33 views
-4

大部分代码似乎没问题,需要部分帮助才能找到最小值。我必须写什么条件才能找到用户输入的最小数字,并将零作为最小数量排除?如何正确找到用户输入的最小值?

#include<iostream>//header 
#include <string> 
using namespace std; 
int main() { 
int n , sentinel = 0, max = 0, min, count = 0, sum = 0; 
double avg; 
cout << "Enter a series of number terminated by 0:" << endl;//prompt user to input a series of number 

do { 
    cin >> n;//read the input 
    for (int i = 0; i < n; i++) { 
     if (n>max) 
      max = n; 
     } 
    for (int i = 0; i < n; i++) { 
     if (n<min) 
      min = n; 
    } 
    sum = sum + n; 
    count++; 



} while (n!= sentinel); 
count--; 
avg = sum/count; 

cout << "You have enter " << count << " integers" << endl;//display how may input user enter 
cout << "Average is " << avg << endl;//display average 
cout << "Max is " << max << endl;//display maximum number 
cout << "Min is " << min << endl;//display minimum number 
    system("pause"); 
    return 0; 

} 
+4

错误的页面。这应该是在https://codereview.stackexchange.com –

+0

你需要一个明智的开始价值'min',但你的代码不能用于最大值(尝试输入负数)或平均值(尝试1和2,或-1和2)。 – molbdnilo

+1

尝试向朋友解释(甚至是虚构的)'for(int i ...'循环的要点是什么 – molbdnilo

回答

0

您可以与您的int min;最大可能值,并为您的int max;的最小可能值开始:

int min = std::numeric_limits<int>::max(); 
int max = std::numeric_limits<int>::min(); 

然后您为min输入必须高于其初始值越小任何而你为max输入的内容必须大于其初始值。

+0

它应该交换,不应该吗? '如果(n max)max = n;'永远不会是真的 –

+0

@AndreKampling heh当然,:) – Galik

相关问题