c - 在 for 循环中中断 if 语句
问题描述
如何在加仑 < 100 和小时 < 24 的情况下在执行后结束循环显示。我能够得到“鱼在……小时后死去”但不确定如何停止 for 循环中的第一个 printf()执行。
我尝试过在 if 语句中使用缩进的 break 语句,但这只会影响 for 循环。
#include <stdio.h>
int main()
{
double add, vol = 500;
int hour;
printf("Please enter additional water added per hour: ");
scanf("%lf", &add);
for (hour = 1; hour <= 24; hour++)
{
vol = (vol * 0.90) + add;
printf("The volume is %.2f gallons after %d hours.\n", vol, hour);
if (hour <= 23 && vol < 100)
printf("The fish died after %d hours.", hour);
else if (hour == 24 && vol >= 100)
printf("Alas, The fish who lived.");
}
return 0;
}
预期结果:
Please enter additional water added per hour: 6
The volume is 456.00 gallons after 1 hours.
The volume is 416.40 gallons after 2 hours.
The volume is 380.76 gallons after 3 hours.
...
The volume is 103.33 gallons after 22 hours.
The volume is 99.00 gallons after 23 hours.
The fish died after 23 hours.
实际结果:
Please enter additional water added per hour: 6
The volume is 456.00 gallons after 1 hours.
The volume is 416.40 gallons after 2 hours.
The volume is 380.76 gallons after 3 hours.
...
The volume is 103.33 gallons after 22 hours.
The volume is 99.00 gallons after 23 hours.
The fish died after 23 hours. The volume is 95.10 gallons after 24 hours.
解决方案
C 不是 Python,缩进在语法上并不重要。复合语句必须包含在{..}
:
if (hour <= 23 && vol < 100)
{
printf("The fish died after %d hours.", hour);
break ;
}
else if (hour == 24 && vol >= 100)
{
printf("Alas, The fish who lived.");
}
我建议您始终使用{..}
条件块或循环块,即使是单个语句。它使维护更简单。
但是,break;
可以说是退出循环的一种相当不雅且结构不佳的方式(与 一起continue
)。更好的结构化解决方案是仅通过循环约束来终止循环。在这种情况下,可以通过以下方式完成:
for( hour = 1;
vol > 100 && hour <= 24;
hour++)
有额外测试的开销,但在比这更复杂的代码中,可能有多个break
s,它可能变得难以维护、调试和理解。
推荐阅读
- python-3.x - 安装python包
- mysql - 只查找一条记录的分组查询(employee_id = 1 或 null)
- c# - 实体框架分页错误:等待操作超时:AddRange
- sql-server-2016 - SQL Server 2016 内存优化表中的 DML 触发器
- xcode - 盛大的中央调度代码放在哪里?
- symfony - 在 symfony 4 中创建数据库时出错?
- c++ - C++中的继承和构造函数定义
- c# - C# 字典过滤 (LINQ) 值并获取密钥
- templates - 通过引用传递容器时,自动参数或模板推导更好吗?
- html - 垂直对齐 svg 内的图像