2013-09-10 45 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