簡體   English   中英

While循環會跳過scanf的條件。

[英]While Loop skipping scanf for it's condition.

我看不到While循環為什么會加快速度並跳過char的scanf嗎? 它甚至不會要求我的輸入,只是像沒有明天一樣循環播放。

#include <stdio.h>


int main()
{
    int number;
    int multiply, ans;
    char choice;

    printf("-------------------------------------");
    printf("\n      MULTIPLICATION TABLE           ");
    printf("\n-------------------------------------");


    do
    {

         printf("\nEnter an integer number:");
         scanf("%d", &number);


        printf("\nMultiplication of %d is :-\n", number);
        printf("\n");

        for(multiply=1; multiply<11; multiply++){
            ans = number * multiply;
            printf(" %d", ans);
        }

        printf("\n");
        printf("\nWould you like to continue? [Y] for Yes,[N] for no : ");
        scanf("%c", &choice);
        printf("\n");

    } 
    while(choice='Y');

    printf("Thank You");
    return 0;

}

scanf()不執行您認為的操作(換行符,緩沖等)。 最好使用fgetc()

choice = fgetc(stdin);

出於相同的原因,您需要擺脫尾隨換行符

scanf("%d", &number");

保留在標准輸入緩沖區中。 要解決此問題,請插入

fgetc(stdin);

在對scanf()特定調用之后。

另外,C不是Pascal。 您要尋找的相等比較運算符-和條件-

while (choice == 'Y')

單個等式標記表示分配。

我認為你需要使用==操作符的比較while條件檢查:

   while(choice=='Y');

當前,您正在使用=運算符,它將Y分配給choice變量。

自從使用該語言編程以來已經有很長時間了,但是一眼就能知道:

while(choice='Y');

代替:

while(choice=='Y');

==比較,=等於。 因此,while循環實際上並未檢查您要設置的條件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM