我的代码用于学校,旨在存储用户输入的汽车的速度,然后查找非超速驾驶者和超速驾驶者的平均速度(超过65的任何人都在超速驾驶)。我的问题是,每次运行此命令时,它只允许我输入一个速度,然后显示平均值,即速度本身。我正在寻找它来重复和存储值,直到输入“ -1”,这应该结束循环。谁能签出我的代码,请帮忙。
#include <stdlib.h>
#include <stdio.h>
void main(void)
{
int count1 = 0;
int count2 = 0;
double speed;
double speeders = 0;
double legals = 0;
double average1;
double average2;
int finished = 0;
while (finished != 1)
{
printf("Enter a speed (or -1 to quit):\n");
scanf("%lf", &speed);
if (speed > 65)
{
printf("SPEEDING\n");
speeders = speeders + speed;
count1++;
}
else if (speed >= 0 && speed <= 65)
{
printf("OK\n");
legals = legals + speed;
count2++;
}
else (speed == -1)
;{
finished = 1;
}
}
average1 = speeders / (double)count1;
average2 = legals / (double)count2;
printf("The average speed of the speeders is: %lf, and the average speed of the non-speeders is: %lf\n", average1, average2);
}
答案 0 :(得分:2)
此处的代码块:
else (speed == -1)
;{
finished = 1;
}
始终将finished
设置为1。您需要:
else if(speed == -1)
{
finished = 1;
}
或简单地:
else
{
finished = 1;
}
答案 1 :(得分:2)
您写道:
else (speed == -1)
;{
finished = 1;
}
请注意错误的分号,并尝试在else
上加条件!
就是这个:
else (speed == -1);
{
finished = 1;
}
…或者这个:
else
{
(speed == -1);
}
{
finished = 1;
}
…或者这个:
else
{
speed == -1;
}
{
finished = 1;
}
…或者这个:
else
{
speed == -1;
}
finished = 1;
…或者这个:
else
{}
finished = 1;
…或者这个:
finished = 1;
换句话说,finished
总是 设置为1
,并且您的else
条件不起作用。
仔细检查语法并仔细阅读代码!