C程序错误负输入不起作用

时间:2018-10-11 03:55:02

标签: c

这是我的代码,我不确定自己做错了什么。这是一个平均最大和最小计算器。该程序在输入正值时起作用,但是当输入值是负值时,它会使所有内容混乱。我认为问题出在数据类型上,所以我试图使其倍增,但仍然无法正常工作,我没有主意。也许它与if语句有关?

#include <stdio.h>
#include <math.h>

int main(void)
{
   double min;
   double sum;
   double max;
   int i;
   int N;
   double Num;
   double avgMean;
   int flag=0;


   printf("MIN, Max, and Mean CALCULATOR\n\n\n");
   printf("How many values are to be entered? :\n");
   scanf("%d", &N);

   sum=0;

   for(i=1; i<=N; i++)
   {flag=0;
   while(1)
   {
      printf("Value %d:\n", i);
      flag=scanf("%lf", &Num);
      if (flag == 0)
      {
         printf("INPUT ERROR!\n");
      }
      else
      {
         break;
      }
   }


   if(i==1||Num>max)
   {
      max=Num;
   }

   if (i==1||Num<min)
   {
      min=Num;
   }

   sum=sum+Num;
}
printf("\n");
avgMean = sum / (float)N;

printf("The minimum value is %g, the maximum value is %g, and the average value is %g.\n", min, max, avgMean);
return 0;
}

1 个答案:

答案 0 :(得分:0)

程序在gcc编译器上使用负数即可正常工作:

首次运行

MIN, Max, and Mean CALCULATOR


How many values are to be entered? :
3
Value 1:
-2
Value 2:
-4
Value 3:
-5
The minimum value is -5, the maximum value is -2, and the average value is -3.66667.

第二次运行

MIN, Max, and Mean CALCULATOR


How many values are to be entered? :
6 
Value 1:
1
Value 2:
3
Value 3:
6
Value 4:
-8
Value 5:
-11
Value 6:
5

The minimum value is -11, the maximum value is 6, and the average value is -0.666667.

第三次奔跑

MIN, Max, and Mean CALCULATOR


How many values are to be entered? :
4
Value 1:
0
Value 2:
0
Value 3:
0
Value 4:
-3

The minimum value is -3, the maximum value is 0, and the average value is -0.75.

但是为了安全起见,请进行以下更改:

if((flag == 0)||(num<0))