【问题标题】:Using 'printf' on a variable in C [closed]在 C 中的变量上使用“printf”[关闭]
【发布时间】:2013-05-21 16:45:42
【问题描述】:
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int x = 1;

    printf("please make a selection with your keyboard\n");
    sleep(1);
    printf("1.\n");

    char input;
    scanf("%c", &input);
    switch (input) {
        case '1':
            x = x + 1;
            printf(x);
    }
    return(0);
}

我正在尝试将一个变量添加到自身,然后将该变量打印出来,但我似乎无法让我的代码工作。

我的输出错误是

newcode1.c: In function ‘main’:
newcode1.c:20:2: warning: passing argument 1 of ‘printf’ makes pointer from integer without a cast [enabled by default]
In file included from newcode1.c:1:0:
/usr/include/stdio.h:362:12: note: expected ‘const char * __restrict__’ but argument is of type ‘int’
newcode1.c:20:2: warning: format not a string literal and no format arguments [-Wformat-security]

【问题讨论】:

  • 顺便说一句,您不是在打印变量,而是在打印某个变量的 [当前]
  • 另外,最好在scanf之前初始化input并测试scanf的结果

标签: c variables


【解决方案1】:

您的printf 需要一个格式字符串:

printf("%d\n", x);

reference page 详细介绍了如何使用printf 及相关功能。

【讨论】:

  • 这就是我需要做的一切?!?!?!谢谢它的工作。
【解决方案2】:

作为Shafik already wrote,您需要使用正确的格式,因为scanf 会为您提供一个字符。

如果您不确定用法,请随时查看printf - C++ Reference

提示:写x = x + 1 更快/更好;更短的方法是:x++;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-02
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多