【发布时间】:2016-08-19 15:19:10
【问题描述】:
程序是,用户将输入开始值、结束值和间隔。输出应该是,start_value 将被添加到间隔中,直到达到结束值。如果输出大于最终值,我想显示一些消息。示例:
Enter start value:5
Enter end value: 30
Enter interval value: 5
Output: 5 10 15 20 25 30 // correct output
2nd try
Enter start value:5
Enter end value: 30
Enter interval value: 6
Output: 5 11 17 23 29 35 // wrong output
我的代码:
while(start_value <= end_value)
{
start_value = start_value + interval_value;
printf("%d ",start_value);
}
【问题讨论】:
-
“当 start_value 大于 end_value 时会产生无限循环”——废话。
-
当 start_value 大于 end_value 时 - 不会。你可能在某处有一些整数溢出。
-
显示的代码与您描述的不同。请使用Minimal Complete Verifiable Example 更新您的问题。
-
如果您的问题是 35 显示在第二个输出中,即使 35 > 30,那是因为您在检查数字之前不会按间隔递增值。由 while 条件检查时的值是 29,然后在示例中添加 6,使其变为 35。我将在 while 循环中设置条件
while((start_value+interval_value) <= end_value)
标签: c loops for-loop while-loop swap