[英]Having trouble with C program output
據我所知,無論其他任何問題,下面的程序都應打印出標題和菜單選項,然后提示用戶輸入。
但是,它絕對不執行任何操作,並且當我停止執行時,它會打印出菜單等,然后由於沒有詢問用戶輸入的選項,因此反復打印“這不是有效的選項”行。
*編輯:我已經完全刪除了循環。 我在程序中所擁有的只是打印標題,打印菜單,要求用戶輸入,直到終止后,控制台仍無任何顯示。 我要求輸入的內容有問題嗎?
EDIT2 :絕對是scanf,沒有它,一切正常。 我運行了帶有附加功能的代碼,以打印出存儲在option中的值,並且在我之前沒有將其設置為0之前要求用戶輸入時,它告訴我-1。 該程序似乎是自動分配選項,而不是去問用戶他們想要什么。
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main ()
{
/*Print Title*/
printf("Maths Quiz Game \n");
printf("\n");
int i;
int rightCount = 0; //count of right answers
int wrongCount = 0; //count of wrong answers
int questions = 0; //user input for number of questions
int exit = 0; //store exit option
int option = 0; //menu option
while(exit == 0) //while loop that keeps program running until exit is chosen
{
/*Menu Options*/
printf("Please choose an option from the menu below. Enter the number of your choice. \n");
printf(" 1. Choose number of questions for this round. (Max = 5) \n");
printf(" 2. Start Quiz \n");
printf(" 3. Display total of right and wrong answers. (Only availanle after quiz) \n");
printf(" 4. Exit Game \n");
scanf("%d", &option); //taking user menu option
/*Error check for any input that is not a valid option. It continues until valid entry*/
while((option != 1) || (option != 2) || (option != 3) || (option != 4))
{
printf("\n That is not a valid option. Please try again. \n");
scanf("%d", &option);
}
while((option != 1) || (option != 2) || (option != 3) || (option != 4))
您輸入的任何選項值都假設1,while()的第一個條件為false,但其余條件為true,因此進入循環並顯示“那不是有效的選項。請重試。” 所以替換|| 與邏輯And(&&) 。
while((option != 1) && (option != 2) && (option != 3) && (option != 4))
現在,如果您輸入正確的輸入,它將不會顯示“那不是有效的選項。請重試”
如何改變
while((option != 1) || (option != 2) || (option != 3) || (option != 4))
{
printf("\n That is not a valid option. Please try again. \n");
scanf("%d", &option);
}
到其他類似的東西
if ((option != 1) || (option != 2) || (option != 3) || (option != 4))
{
printf("\n That is not a valid option. Please try again. \n");
// scanf("%d", &option); // This is probably not required
}
要么
if ( option >= 1 && option <= 4)
{
printf("\n That is not a valid option. Please try again. \n");
// scanf("%d", &option);
}
由於您在外部使用無限循環,為什么在內部需要一個無限循環? 您只需要檢查選項並顯示菜單(如果選擇了不可用的選項)。
所有你的邏輯,你可以把這個if
以后,每個選項進行選擇。
更好地使用switch
以獲得更好的理解
/* After selecting an option */
switch (option)
{
case 1:
/* Do the operation according */
break;
case 2:
/* Do the operation according */
break;
case 3:
/* Do the operation according */
break;
case 4:
/* Do the operation according */
break;
default:
/* If none of the option selected */
printf ("Wrong input! \n")
break;
}
希望你明白了。
問題與printf函數有關,因為它直到您輸入以下選項后才打印出來,直到用戶回答后才問。 在printf整理出此內容之后進行一次簡單的沖洗。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.