2013-09-10 44 views
1

我的代碼是這個printf()的呈現奇怪的結果

#include<stdio.h> 
int main(void) 
{ 
    unsigned short height = 0; 
    unsigned short width = 0; 
    const unsigned short MIN_SIZE = 3; 
    printf("Enter the values for the width and the height minimum of %u\n:", 
      MIN_SIZE); 
    scanf(" %hd %hd", &width, &height); 
    if (width < MIN_SIZE) 
    { 
     printf("The value of width %u is too small. I set this to %u \n", 
       width, MIN_SIZE); 
     width = MIN_SIZE; 
    } 
    if (height < MIN_SIZE) 
    { 
     printf 
      ("The value of height %u is too small. I setting this to %u \n"), 
      height, MIN_SIZE; 
     height = MIN_SIZE; 
    } 
    for (unsigned int i = 0; i < width; ++i) 
    { 
     printf("*"); 
    } 
    return 0; 
} 

當我給的7例如一個寬度,和0高度,printf()的呈現奇異數。你能解釋一下爲什麼會發生這種情況?

+5

此外,當你說,它提出了「奇怪的結果」,你這是什麼意思呢? – qaphla

+1

不知道實際輸出是什麼,不,我們不能。 – DiMono

+0

你使用什麼編譯器?它不是給出「格式太少的參數」警告或類似的嗎? –

回答

6

這可能會編譯一個警告。提供所有參數後,需要保留右括號。

printf 
      ("The value of height %u is too small. I setting this to %u \n"), 
      height, MIN_SIZE; 

也許你的意思是:

printf("The value of height %u is too small. I setting this to %u \n", height, MIN_SIZE); 

的主要問題是,我們應該用 「%虎」 的簡稱intergers。我想試試這個:

#include<stdio.h> 
int main(void) 
{ 
    unsigned short height = 0; 
    unsigned short width = 0; 
    const unsigned short MIN_SIZE = 3; 
    int i ; 
    printf("Enter the values for the width and the height minimum of %u\n:", MIN_SIZE); 
    scanf(" %hu %hu", &width, &height); 
    if (width < MIN_SIZE) { 
     printf("The value of width %hu is too small. I set this to %hu \n", width, MIN_SIZE); 
     width = MIN_SIZE; 
    } 
    if (height < MIN_SIZE) { 
     printf("The value of height %hu is too small. I setting this to %hu \n", height, MIN_SIZE); 
     height = MIN_SIZE; 
    } 
    for (i = 0; i < width; ++i) 
    { 
     printf("*"); 
    } 
    return 0; 
} 

有對SO這個良好的相關討論:What is the format specifier for unsigned short int?

+2

它編譯(逗號運算符),但任何體面的編譯器都應該警告有更多的'%'轉換比數據參數。 –

+0

+1查找問題。但有趣的是,它將在'gcc'中用C99標準進行編譯。 – lurker

+0

我的意思是,當我設置例如寬度7和高度0 printf()呈現正確的寬度,但在高度打印像2476842 – paulakis