printf()呈现出奇怪的结果

时间:2013-09-10 19:55:32

标签: c 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()会显示奇怪的数字。你能解释一下为什么会这样吗?

1 个答案:

答案 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);

主要问题是我们应该使用“%hu”来做短暂的唠叨。我会试试这个:

#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;
}

关于此问题,有一个很好的相关讨论:What is the format specifier for unsigned short int?