【问题标题】:printf() presents weird resultsprintf() 呈现奇怪的结果
【发布时间】:2013-09-10 19:55:32
【问题描述】:

我的代码是这样的

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

【问题讨论】:

  • 另外,当你说它呈现“奇怪的结果”时,你的意思是什么?
  • 不知道实际输出是什么,不,我们不能。
  • 你使用什么编译器?它不会给出“格式参数太少”警告或类似警告吗?

标签: c printf


【解决方案1】:

这可能会在编译时出现警告。提供所有参数后,您需要保留右括号。

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?

【讨论】:

  • 它确实可以编译(逗号运算符),但任何体面的编译器都应该警告说,'%' 转换比数据参数多。
  • +1 用于发现问题。但有趣的是,它将使用gcc 中的C99 标准编译。
  • 我的意思是当我设置例如宽度 7 和高度 0 printf() 正确呈现宽度但在高度上打印类似 2476842 的东西
  • @Martin R,我同意 (+1)。我已将答案更新为更准确。
  • 我会说是的。因为 "%hd" 是一个 short 并且 "%hu" 是一个 unsigned short 。
猜你喜欢
  • 2012-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多