#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main() {
double a;
int x,z,b;
x = 0;
z = 0;
a = 0;
while (x != -1){
a += 1;
scanf("%d",&x);
z += x;
}
b = z / a;
printf("%f",b);
}
代码修正如下,输入数字时,最后以输入-1作为结束;b = (z1.0+1) / (a1.0-1),z和a乘以1.0是为了整型转浮点,z加1是因为最后一次输入-1,被统计在z里面,a减一是将输入次数统计去掉最后输入-1这一次
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main() {
double b;
int x,z,a;
x = 0;
z = 0;
a = 0;
while (x != -1){
a += 1;
scanf("%d",&x);
z += x;
}
b = (z*1.0+1) / (a*1.0-1);
printf("%f",b);
}
验证结果如下:
3
3
3
-1
3.000000
3
4
3
-1
3.333333
1、你定义的b是 整型的,z、a也是整型的,那么b=z/a也是整型的。
2、你最后的打印是%f,类型有冲突。
3、首先你要先吧这些弄一致了,另外注意,转换成double的时候,先转换类型在计算。
b改成double类型。输出用%lf