我是编码新手,从C开始。 我正在处理的程序让我因用户输入而挂断电话。我应该找到用户输入的最小值和最大值,但到目前为止我没有尝试过任何工作。 任何帮助将不胜感激:
#include <stdio.h>
#include <math.h>
int main() {
int i;
int n;
float data;
float sumx;
float sumx2;
float mean;
float var;
float sd;
int min;
int max;
/* Get the number of data lines from the user*/
printf("How many numbers do you need to enter (n)? ");
scanf("%d", &n);
while (n <= 0) {
printf("Enter positive numbers only, please.\n");
printf("\n");
printf("How many numbers do you need to enter (n)? ");
scanf("%d", &n);
/* Initialization */
sumx = sumx2 = 0.0;
for ( i = 1; i <= n; i++) {
printf("Enter data item %d: ", i);
scanf("%f", &data);
min = 0;
max = 0;
if(data > max)
max = data;
else if(data < min)
min = data;
sumx = sumx + data;
sumx2 = sumx2 + (data * data);
}
mean = sumx / n;
var = 1.0/(n-1) * (sumx2 - (1.0/n) * sumx * sumx);
sd = sqrt(var);
printf("\n");
printf("The minimum value entered: %d\n", min);
printf("The maximum value entered: %d\n", max);
printf("\n")
printf("mean = %f\n", mean);
printf("variance = %f\n", var);
printf("std. dev. = %f\n\n", sd);
return 0;
}
无论在程序中输入什么值,最小值都读为0,最大值是最后输入的值。 最小值/最大值是否应该不同?
答案 0 :(得分:1)
你走在正确的轨道上。由于一些严重的语法错误,您的程序将无法编译。
以下是diff相对于工作版本的输出:
25,26c25,28
< scanf(%d", &n);
<
---
> scanf("%d", &n);
>
> }
>
29c31
< sumx = sumx2 = 0.0
---
> sumx = sumx2 = 0.0;
39c41
< mean = sums / n;
---
> mean = sumx / n;
46a49,50
>
> return 0;
更正的错误如下:
编译器也会期望返回值,但如果丢失则很可能只生成警告。值得注意的是,while循环不能做任何有用的事情,但如果用户输入的数字小于或等于零,它会导致无限递归。
你的for循环中需要的逻辑如下:
sumx = sumx2 = 0.0;
max = 0;
min = 0;
for ( i = 1; i <= n; i++) {
printf("Enter data item %d: ", i);
scanf("%f", &data);
if(data > max)
max = data;
else if(data < min)
min = data;
if( i ==1 )
min = data;
sumx = sumx + data;
sumx2 = sumx2 + (data * data);
}
可能还有其他逻辑错误。如果您需要更多帮助,请告诉我。
祝你好运!答案 1 :(得分:1)
min = 0;
max = 0;
for ( i = 1; i <= n; i++) {
printf("Enter data item %d: ", i);
scanf("%f", &data);
if(data > max)
max = data;
if(data < min)
min = data;
if(i == 1){min = data;}
sumx = sumx + data;
sumx2 = sumx2 + (data * data);
}
EDIT(以上代码不适用于data = 0的初始值)
min = INT_MAX; //chux suggestion
max = INT_MIN;
for ( i = 1; i <= n; i++) {
printf("Enter data item %d: ", i);
scanf("%f", &data);
if(data > max)
max = data;
if(data < min)
min = data;
sumx = sumx + data;
sumx2 = sumx2 + (data * data);
}
并更正while
循环
瓦尔特