簡體   English   中英

如果用戶未輸入正確的值,則使C程序重新開始並再次請求輸入

[英]Making a C program return to the start and ask for input again if a user did not input the right value

這是我的第一篇文章,所以請對我溫柔。 我最近在大學里開始了C編程課程,對此我真的很感興趣。 由於我正在使用音頻(混合/母帶音樂),因此我決定嘗試制作一個簡單的程序,該程序將為用戶定義的BPM(每分鍾節拍)計算以毫秒為單位的延遲時間。

我目前遇到的問題是:我希望程序返回到開始並要求用戶再次輸入是否輸入了錯誤的BPM(在這種情況下為0)。

我嘗試了一個do while循環,但是它運行不正常,我的程序仍會計算所有內容,就好像用戶只是鍵入0一樣,如果我鍵入了正確的值,它將無限循環。

如果我執行if else語句,它將向用戶顯示一條消息,但我想提示用戶再次輸入該消息。

我知道這是一個非常簡單和基本的問題,但是任何幫助將不勝感激。

到目前為止,這是我的代碼:

int main(){

    float BPM;

    printf("Please input the BPM:   ");
    scanf(" %f", &BPM);

    do{

    float HZ = 1000;
    float HZ_Result;
    float BPM_QuarterNote=(60/BPM)*1000;

    float BPM_WholeNote=BPM_QuarterNote*4;
    printf("\n\nDelay time for whole note is: %.2f ms or %.2f Hz", BPM_WholeNote, 1000/BPM_WholeNote);

    float BPM_HalfNote=BPM_QuarterNote*2.0;
    printf("\n\nDelay time for 1/2 note is: %.2f ms or %.2f Hz", BPM_HalfNote, 1000/BPM_HalfNote);

        printf("\n\nDelay time for 1/4 note is: %.2f ms or %.2f Hz", BPM_QuarterNote,  1000/BPM_QuarterNote);

    float BPM_EightNote=BPM_QuarterNote*0.5;
    printf("\n\nDelay time for 1/8 note is: %.2f ms or %.2f Hz", BPM_EightNote, 1000/BPM_EightNote);

    float BPM_SixteenthNote=BPM_QuarterNote*0.25;
    printf("\n\nDelay time for 1/16 note is: %.2f ms or %.2f Hz", BPM_SixteenthNote, 1000/BPM_SixteenthNote);

    float BPM_32ndNote=BPM_QuarterNote*0.125;
    printf("\n\nDelay time for 1/32 note is: %.2f ms or %.2f Hz", BPM_32ndNote, 1000/BPM_32ndNote);


    }while(BPM > 0);

return 0;
}

您可以使用while循環代替if來測試您的狀況

例如

/* while loop execution */
while( BPM == 0 ) {
/* get my input values */
}

一個簡單的用戶輸入循環示例,僅當用戶滿意時退出:

int main(void)
{
    float fNum= 5.2;
    double dpNum= 5.2;
    long double ldFloat;

    char quit[]={" "};

    while(quit[0] != 'q')
    {
        printf("\n\nEnter a float number: ");
        scanf("%f", &fNum);
        printf("Enter a double precision number: ");
        scanf("%Lf", &ldFloat);
        ... other stuff as needed
        printf("Enter any key to continue or 'q' to exit.");
        scanf("%s", quit);
    }
    return 0;
}

在BPM聲明下面添加此代碼。

do{
    printf("Please input the BPM:   ");
    scanf(" %f", &BPM);
  }while(BPM==0.00);
do {
    printf("Please input the BPM: ");
} while (scanf("%f", &bpm) == 0 || bpm < 0);

此循環將打印問題,直到用戶輸入有效的浮點數並且該數至少為0。

暫無
暫無

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

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