【问题标题】:How to printf Variables correctly in C?如何在 C 中正确打印变量?
【发布时间】:2019-02-17 18:56:00
【问题描述】:

今天是我第一次使用 C,我尝试了一些东西,比如 if、getchar() 等。但现在我的问题是,我的代码中的第三个 printf() 打印了它不应该打印的东西。但我不知道问题出在哪里。

循环应该采用 c 整数,并且应该在每个“循环”中添加“1”。但是当我输入“5”时,循环打印:

You entered: 54
You entered: 55
You entered: 56
You entered: 57
You entered: 58
You entered: 59
You entered: 60
You entered: 61
You entered: 62
You entered: 63
You entered: 64
You entered: 65
You entered: 66
You entered: 67

但它应该打印如下内容:

You entered: 6
You entered: 7
You entered: 8
You entered: 9
You entered: 10
You entered: 11
You entered: 12
You entered: 13
You entered: 14
You entered: 15
You entered: 16
You entered: 17
You entered: 18
You entered: 19

我的代码

#include <stdio.h>
int main()
{
    printf("Enter a value!: ");
    int c = getchar();
    printf("You entered: %c\n", c);

    int x = 1;

    while(x < 15) {
     x++;
     c++;
     printf("You entered: %d\n", c);
    }

    return 0;
}

【问题讨论】:

  • getchar() 获取字符而不是整数。 5 的 ascii 是 53,这就是它从 54 开始的原因。
  • 使用scanf() 而不是getchar() 来获取数字。

标签: c


【解决方案1】:

当您使用getchar() 扫描一个数字时,您将其扫描为一个字符。所以变量存储了5ascii value,即53。因此,当您使用%d 打印c 的值时,它会打印c 的ascii 值。当您在打印之前将值增加 1 时,它会打印 You entered: 54(53+1)。要获得5,您需要从c 子结构“0”的ascii 值48。您可以使用以下两个示例中的任何一个替换您的第三个 printf。两者都可以正常工作。

printf("You entered: %d\n", c-'0');

或者,

printf("You entered: %d\n", c-48);

【讨论】:

  • 值得注意的是,getchar() 确实返回了 int,但它主要是为了能够返回与任何可能的字符不同的 EOF
【解决方案2】:

将数字与这些数字的表示混淆是一个非常常见的编程错误。它们是完全不同的东西。无论我们写成“五”、“5”还是“IIIIII”,五都是同一个数字。但这些是代表该数字的非常不同的字符序列。

数字五,即您每只手上可能有的手指数,与通常用来表示该数字的字符“5”不同。您正在读取字符,然后将它们作为数字输出。

【讨论】:

    猜你喜欢
    • 2022-01-20
    • 1970-01-01
    • 2020-01-24
    • 2019-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    相关资源
    最近更新 更多