我想编的程序是这样的:
Enter the gallons used(-1 to end):12.8
Enter the miles driven:287
The miles/gallon for this tank was 22.421875
Enter the gallons used(-1 to end):10.3
Enter the miles driven:200
The miles /gallon for this tank was 19.417475
Enter the gallons used(-1 to end):5
Enter the miles driven :120
The miles/gallon for this tank was 24.000000
Enter the galons used (-1 to end ): -1
The overall average miles /gallon was 21.601423
我所编的程序如下:
#include<stdio.h>
main()
{
float gallons,miles,result,average,counter,total;
counter=0;
total=0;
while(gallons!=-1){
printf(“\nEnter the gallons used(-1 to end):”);
scanf(“%f”,&gallons);
printf(“\nEnter the miles driven:”);
scanf(“%f”,&miles);
result=miles/gallons;
counter=counter+1;
printf(“The miles/gallon for this tank was%f\n”,result);}
if(gallons=-1){
total=result+result;
average=(float)total/counter;
printf(“\nThe overal average miles/gallon was%f”,average);}
}
请问这里有什么错误,我非常渴望知道自己的错误,因为我还是菜鸟。
>> 本文固定链接: http://www.vcgood.com/archives/2843
if 语句只能进行一次运算,应植入while 语句中!
网费有限,要先下了!自己看着改改吧!!
上面提议还是不行啊,请哪位高手指点一下,求求你们!
你自己看一下程序,当输入-1时,还要输入the miles driven:
printf(“\nEnter the gallons used(-1 to end):”);
scanf(“%f”,&gallons);
printf(“\nEnter the miles driven:”);
scanf(“%f”,&miles);
肯定和结果不同啊
读书有错误,当输入-1时应该立刻退出循环,加个if判断即可。
if(gallons=-1){
total=result+result;
average=(float)total/counter;
}
这部分也有问题,当-1的时候才执行累加且是result+result,这只是把最后一次的result加了2遍。就是你题目中输入-1后仍要输入个miles,这个result就是-1除以这个后输入的miles,结果当然不对。
一般情况下可以先定义个死循环,然后在scanf后加判断。
并且在循环里面做累加,在循环外求平均值。
下面是我改过的程序,已经调试通过了,你再好好看看,最后的平均值不是21.601423,而是21.94645,你的这个程序和我用计算器算的结果都是21.94645
#include<stdio.h>
main()
{
float gallons,miles,result,average,counter,total;
counter=0;
total=0;
while(1) \*定义个死循环*\
{
printf(“\nEnter the gallons used(-1 to end):”);
scanf(“%f”,&gallons);
if(gallons==-1) break;\*加个判断当输入-1时应该立刻退出循环*\
printf(“\nEnter the miles driven:”);
scanf(“%f”,&miles);
result=miles/gallons;
counter=counter+1;
printf(“The miles/gallon for this tank was %f\n”,result);
total+=result; \*这样才能把每次的result都加到total里*\
}
average=total/counter;
printf(“\nThe overal average miles/gallon was %f”,average);
}