2016-08-03 52 views
-2

我不知道爲什麼這種崩潰在我的機器上,但它確實當輸入大於9時,爲什麼這個程序崩潰?

給你一個正整數,N,:

如果1 < = N < = 9,然後打印它的英文表達。 1是「一」,2是「二」,依此類推。 否則打印「大於9」(不含引號)。 輸入格式:

輸入將只包含一個整數N。

#include <stdio.h> 

const char* itos2(int); 

int main() { 
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 
    int a; 
    scanf("%i", &a); 
    printf("%s",((a >= 1 || a <= 9) ? itos2(a) : "Greater than 9")); 

    //printf("%s",itos2(a)); this doesn't crash provided a default label is set 
    return 0; 
} 

const char* itos2(int a) 
{ 
const char* str [] = { "one" , "two", "three", "four", "five", "six", "seven", "eight", "nine"}; 
    switch(a) 
    { 
     case 1 : return str[0]; 
     case 2 : return str[1]; 
     case 3 : return str[2]; 
     case 4 : return str[3]; 
     case 5 : return str[4]; 
     case 6 : return str[5]; 
     case 7 : return str[6]; 
     case 8 : return str[7]; 
     case 9 : return str[8]; 
     default: return "Greater than 9"; 
    } 
} 
+0

你的條件'(一> = 1 || a <= 9)'表示'a'可以是'> = 0'或'<= 9'。注意'或'條件。這意味着如果輸入是'15',這個數字大於'1',這使得你的條件成立。如果輸入是'-5',這意味着這個數字小於'9',也使條件成立。注意'或'。 – alvits

+0

@alvits爲什麼在評論中回答而不是實際的答案? –

+0

謝謝你,我明白了爲什麼這個默認標籤導致問題,我的編譯器沒有拋出任何「控制達到void語句警告結束」,所以我也責怪 – hec

回答

0

這裏是你的代碼,改進:

#include <stdio.h> 

const char* itos2(int); 

// A proper C function prototype 
int main(void) 
{ 
    int a; 

    // Checking the return value of scanf is *required*! 
    // If it doesn't return a value which is equal to the number of expected 
    // assignments, then your variables are left unassigned, leading to 
    // Undefined Behavior! 
    if (scanf("%i", &a) != 1) { 
     fprintf(stderr, "Invalid input\n"); 
     return 1; 
    } 

    // It's usually better practice to not have to worry about a valid range 
    // of inputs when calling a function. Let this function worry about the 
    // input checking. 
    printf("%s", itos2(a)); 

    return 0; 
} 

const char* itos2(int a) 
{ 
    const char* str [] = { 
     "zero", 
     "one", 
     "two", 
     "three", 
     "four", 
     "five", 
     "six", 
     "seven", 
     "eight", 
     "nine", 
    }; 

    // Check boundary conditions. Checking just one boundary case and 
    // returning is simpler and less error-prone than your previous code. 
    if (a < 0) 
     return "Less than zero"; 
    if (a > 9) 
     return "Greater than nine"; 

    // Why bother with a switch/case statement when you can simply 
    // use the input value to index directly into an array of the strings? 
    return str[a]; 
} 

假設你使用GCC,總是編譯至少這組選項:

gcc -Wall -Werror ... 
+0

我喜歡這種優化! – hec

+0

@hec務必告訴你的老師,答案是從計算器 - 信用信用到期:-) – pm100

+0

虐待它添加到源代碼,問題來自黑客等級 – hec

4

條件a >= 1 || a <= 9總是正確的,這意味着你的itos2總是不管你輸入的被稱爲a。如果a不在[1, 9]範圍之內,則函數itos2無法返回任何內容,從而產生未定義的行爲(在您的情況下發生崩潰)。

顯然你的意思是a >= 1 && a <= 9作爲你調用itos2的條件。 &&,而不是||

相關問題