您的位置:首页 > 其它

算法:汽车在有里程标志的公路上行驶,从键盘输入开始和结束的里程及时间(以时、分、秒输入),计算并输出其平均速度(千米/小时)

2017-10-23 13:32 1696 查看
#include "stdio.h"

int main(void)
{
float time = 0, velocity = 0;
float startDistance = 0, endDistance = 0;
float startHour = 0, startMinute = 0, startSecond = 0;
float endHour = 0, endMinute = 0, endSecond = 0;

//开始及结束的里程数
printf("请输入汽车开始的里程(单位:千米):");
scanf_s("%f", &startDistance);
printf("请输入汽车结束的里程(单位:千米):");
scanf_s("%f", &endDistance);

//开始及结束的时间
printf("请输入汽车开始的时间(时、分、秒之间用空格隔开):");
scanf_s("%f %f %f", &startHour, &startMinute, &startSecond);
printf("请输入汽车结束的时间(时、分、秒之间用空格隔开):");
scanf_s("%f %f %f", &endHour, &endMinute, &endSecond);

//计算总用时
time = (endHour + endMinute / 60 + endSecond / 360) - (startHour + startMinute / 60 + startSecond / 360);
//计算平均速度
velocity = (endDistance - startDistance) / time;

printf("汽车的平均速度为:%f 千米/小时\n", velocity);

return 0;
}


以上代码仍然有一些问题,比如需要考虑到小时、分钟和秒钟的取值范围。

以下为修改后的代码

#include "stdio.h"

int main(void)
{
float time = 0, velocity = 0;
float startDistance = 0, endDistance = 0;
float startHour = 0, startMinute = 0, startSecond = 0;
float endHour = 0, endMinute = 0, endSecond = 0;

//开始及结束的里程数
printf("请输入汽车开始的里程(单位:千米):");
scanf_s("%f", &startDistance);
printf("请输入汽车结束的里程(单位:千米):");
scanf_s("%f", &endDistance);

//开始及结束的时间
printf("请输入汽车开始的时间(时、分、秒之间用空格隔开):");
scanf_s("%f %f %f", &startHour, &startMinute, &startSecond);
printf("请输入汽车结束的时间(时、分、秒之间用空格隔开):");
scanf_s("%f %f %f", &endHour, &endMinute, &endSecond);

//判断时间格式是否正确
if ((0 <= startHour && startHour < 24) && (0 <= startMinute && startMinute < 60) && (0 <= startSecond && startSecond < 60) &&
(startHour <= endHour && endHour < 24) && (0 <= endMinute && endMinute < 60) && (0 <= endSecond && endSecond < 60))
{
//计算总用时
time = ((endHour + endMinute / 60 + endSecond / 360) - (startHour + startMinute / 60 + startSecond / 360));
//计算平均速度
velocity = (endDistance - startDistance) / time;

printf("汽车的平均速度为:%f 千米/小时\n", velocity);
}
else
printf("时间格式错误!\n");

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 velocity
相关文章推荐