2014-03-12 86 views
0

我試圖讓這段代碼在有人輸入負值或者甚至整數時給出錯誤。我有負整數,但我似乎無法找到一種方式來讓系統在輸入偶數時輸出錯誤消息。查找整數

#include <stdio.h> 

int main(void){ 

    int size, i, j, spaces, stars, true, false; 


    printf("How many rows do you want?\n"); //ask the user how many rows they want 
    scanf("%d", &size); 

    //this check to make sure a positive, odd integer is entered 
    if(size <= 0) 
     printf("sorry, but you need to input a positive, odd integer.\n"); 


    int mid = size/2 +1; //this is to find the midpoint of the diamond where you will start decrementing 

    //menu options 


    //this is the for loop that will create your rows 
    for(i = 1; i <= size; i++){ 
      if(i < mid){ 
       spaces = mid - i; 
       stars = size - (spaces*2); 
      } 
      if(i > mid){ 
       spaces = i - mid; 
       stars = size - (spaces*2); 
      } 
      if (i == mid){ 
       spaces = 0; 
       stars = size; 
      } 

     for(j = 0; j < spaces; j++) 
      printf(" "); 
     for(j = 0; j < stars; j++) 
      printf("*"); 

     printf("\n"); 

    } 
    return 0; 
} 
+0

這不是你問的問題,但你可能想錯誤檢查後的返回語句......就像它會打印錯誤消息,然後保持正確的狀態。 – user3303729

回答

3
if(size % 2 == 0) 
    printf("sorry, even integer not allowed.\n"); 
1
//this check to make sure a positive, odd integer is entered 
if(size <= 0 || size%2==0) 
    printf("sorry, but you need to input a positive, odd integer.\n"); 

編輯:如果你想停止這種錯誤後執行 - 只需使用return

//this check to make sure a positive, odd integer is entered 
if(size <= 0 || size%2==0) 
{ 
    printf("sorry, but you need to input a positive, odd integer.\n"); 
    return 1; // A return value different than 0 usually indicates an error 
} 
+0

但是,如果輸入的內容不符合這些參數,程序將繼續運行。我應該把它放在一個循環中嗎? – user3230393

+0

哇謝謝我不知道有關返回值。謝謝! – user3230393