2016-12-26 67 views
-2

:(處理的高度爲0正確\預期的退出代碼0,而不是輸出「\ n請輸入一個正整數VALU ......」check50錯誤信息:在我的Mario.c PSET1解決方案

:(拒絕的「」 \預期產出,而不是提示輸入一個非數字的高度

https://sandbox.cs50.net/checks/5593ad8059ce4492804c07aff8e377eb

我想我應該把我的代碼部分太:

#include <stdio.h> 


int clean_stdin() 
    { 
     while (getchar()!='\n'); 
     return 1; 
    }        //snippet gotten from http://stackoverflow.com/questions/14104013/prevent-users-from-entering-wrong-data-types 


int main (void) 
{ 
    int row, pyramid_height, space, hash; 
    char c;    

    do 
    { 
     printf("\n Please enter a positive integer value, less than 24 as the height: ");  

    }   
    while (((scanf("%i%c", &pyramid_height, &c) != 2 || c!='\n') && clean_stdin()) || pyramid_height < 1 || pyramid_height > 23); 
        //snippet gotten from http://stackoverflow.com/questions/14104013/prevent-users-from-entering-wrong-data-types   

請幫忙:

另外,有沒有一種更簡單的方法來防止用戶輸入錯誤的數據? 謝謝。

回答

0

你應該做這樣的事情來要求用戶輸入

printf("Enter height < 23 and a non-negative number\n"); 
do{ 
    printf("Height: "); 
    height = GetInt(); // ask user again until valid input is given 
}while(height < 0 || height >23); 

如果你不想使用GetInt(),您可以用scanf函數做到這一點。只需將GetInt行替換爲scanf("%d",&height);即可。它會工作相同,除非輸入一個錯誤的號碼,它會通過說Height: 而不是Retry:來大聲說出你的名字。

而你應該刪除那個clean_stdin函數。在pset1中不需要這種精確度。

現在剩下的部分是你未在問題中提供的嵌套循環,所以我假設你也有問題,因爲你的程序無法正確處理0。

嘗試類似這樣的代替for循環。

for(int i=1; i<=height; i++){     // i number of #s in each step 
    for(int j=0; j<height-i; j++){   //print appropriate number of spaces 
     printf(" "); 
    } 
    for(int k=0; k<=i; k++){     //print #s 
     printf("#"); 
    } 
    printf("\n");        //change line 
} 
+0

謝謝!...我沒有for循環的問題。因特網是昂貴的,所以我使用離線編譯器Dev C++並且沒有使用cs50.h庫。不知道GetInt()函數是否有效。 –

+0

如果解決了您的問題,您可以接受答案。 –

+0

@AdeyomolaAdebayo同時檢查答案中的編輯。如果你不想使用cs50庫,你可以做到這一點。 –