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

标签 c loops for-loop while-loop swap

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

最佳答案

您需要一个决定性的 if 条件。并且,在执行增量之前移动 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;

}

关于c - 我应该使用什么循环以及如何使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39042597/

相关文章:

c - 为什么有些内核程序员使用 goto 而不是简单的 while 循环?

c# - C# 中的 Foreach 与 for 循环。在 for 循环中可以创建新对象,但在 foreach 循环中是不可能的

python - 循环帮助: it doesn't wait for loadFinished SIGNAL in PyQt4

xml - XQuery 嵌套循环的自动增量辅助索引 var

c++ - 我如何从 C/C++ 访问局部变量或调用 lua 脚本中的局部函数?

c++ - 将 long int 转换为结构指针

c - 我正在尝试打印电话号码,但出现错误

C 预处理器与变量的连接

python - 如何通过删除列表中的特定元素来运行给定列表的 itertools 产品?

java 替换数组的元素