【问题标题】:How could i continue this loop in C我怎么能在 C 中继续这个循环
【发布时间】:2016-03-05 04:15:46
【问题描述】:

我试图在两个循环中输出相同数量的 printf 语句,我必须使用 for 和 while 。不幸的是,我的第二个循环出现了无限循环。我在第二个循环中做错了什么?

#include <stdio.h>
#define _CRT_SECURE_NO_WARNINGS

int main()
{
    int x,c,v,b;
    printf("Please enter a number between 1 and 25 \n");
    scanf_s("%d",&x,&c);

    for (x != 0; x--;)
    {

        printf("I'd rather be doing something else \n");
    }
    while (c!=0 ) {
        printf("Programming is easy");
        c--;
    }
}

【问题讨论】:

    标签: c loops for-loop while-loop


    【解决方案1】:
    scanf_s("%d",&x,&c);
    

    在这个 scanf 中你只得到一个值。
    这里变量c 正在获得一些垃圾值,因此它可能会运行很长时间,您认为它是无限循环。
    使用

    scanf_s("%d %d",&x,&c);
    

    根据 for 循环语法。

    for(variable initialization; condition; variable update)  
    

    在您的代码中,您已经拥有变量 x 的值。
    条件检查x != 0
    变量更新x--

    应该是这样的

    for( ;  x != 0; x--)
    

    编辑:
    如何让用户提示输入一系列数字,直到用户输入 -1 停止。

    您可以使用的简单代码是。

    scanf("%d,&a);
    while(a != -1)
    {
        //do work here
        //
        //
        //-----
        scanf("%d,&a);
    }
    

    【讨论】:

    • while (c
    • while (c&lt;=1 ) 应该是 while (c &gt;= 1 )
    • for (x != 0; x--;) -> for (;x != 0 ;x--) 。注意分号;的位置
    • 我如何使用 1 个输入而不是 2 个输入来做到这一点
    • @ameyCU,根据 for 循环语法,你是对的,但这也可以正常工作。我也会在我的回答中包含这个。
    猜你喜欢
    • 1970-01-01
    • 2012-02-27
    • 2017-09-18
    • 1970-01-01
    • 1970-01-01
    • 2020-08-14
    • 1970-01-01
    • 1970-01-01
    • 2017-06-25
    相关资源
    最近更新 更多