我应该使用什么循环以及如何使用?

What loop should I use and how?

程序是,用户将输入开始值、结束值和区间。输出应该是,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);                          
}

您需要一个判断条件。并且,在执行增量之前移动您的 printf() 语句。

如果start_value>end_value,则交换它们; 否则,继续相同的循环。

为方便起见,引入一个临时变量来交换值。

if(start_value > end_value){
temp = start_value;
start_value = end_value;
end_value = temp;
}

while(start_value <= end_value)
{
   printf("%d ",start_value);
   start_value = start_value + interval_value;

}

通常,如果您知道起点和终点(输入变量算作已知),For 循环是行业标准。

如果您担心起始值大于结束值的情况,您应该在进入循环之前包含验证代码。我建议有一个接受输入变量和检查的函数,然后允许程序继续或提示用户输入有效。

编辑:你的代码也没有无限循环,因为数字会增加直到达到最大整数(大约 20 亿),循环到最小整数(大约负 20 亿)并且继续前进,直到达到最终值。但是,您没有使用 printf("\n"); 清除缓冲区,这可能是您的问题所在。此外,如果 while 循环条件中描述的条件不正确,您可能只是在起始值更大时没有输入它。

逻辑上当条件变为假时,循环终止。最好将所有代码放在变量中以查看发生了什么,但是
您可以在循环内使用适当的 ifbreak 语句来随时中断循环的执行。

您需要先打印,然后递增。

while(start_value <= end_value)
{
    printf("%d ",start_value);                          
    start_value = start_value + interval_value;             
}