C语言 printf 一个 C 中的变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16675287/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
printf a variable in C
提问by Dave
#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);
}
I am trying a make a variable add to itself and then print that variable out but I can't seem to get my code to work.
我正在尝试将一个变量添加到自身,然后将该变量打印出来,但我似乎无法让我的代码工作。
my output error is
我的输出错误是
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]
回答by Shafik Yaghmour
Your printfneeds a format string:
您printf需要一个格式字符串:
printf("%d\n", x);
This reference pagegives details on how to use printfand related functions.
此参考页面提供了有关如何使用printf和相关功能的详细信息。
回答by Ms. Nobody
As Shafik already wrote you need to use the right format because scanfgets you a char.
Don't hesitate to look here if u aren't sure about the usage: http://www.cplusplus.com/reference/cstdio/printf/
正如 Shafik 已经写的那样,你需要使用正确的格式,因为scanf你会得到一个字符。如果您不确定用法,请不要犹豫,看看这里:http: //www.cplusplus.com/reference/cstdio/printf/
Hint: It's faster/nicer to write x=x+1; the shorter way: x++;
提示:写起来更快/更好x=x+1;更短的方法:x++;
Sorry for answering what's answered just wanted to give him the link - the site was really useful to me all the time dealing with C.
抱歉回答了回答只是想给他链接 - 该网站一直对我处理 C 非常有用。

