c语言入门问题
请问为什么编译不成功?1 #include <stdio.h>
2
3 int main()
4 {
5
6 int i;
7 char j;
8 float k;
9
10 i=123;
11 j='c';
12 k=3.14;
13
14 printf("size of int is %d\n",sizeof(int));
15 printf("size of char is %d\n",sizeof(char));
16 printf("size of k is %d\n",sizeof k);
17return 0;
18 }
19
下面是错误提示:
xinruiliu~/1/1-1$ gcc 1.c
1.c:14:30: warning: format specifies type 'int' but the argument has type
'unsigned long' [-Wformat]
printf("size of int is %d\n",sizeof(int));
~~ ^~~~~~~~~~~
%lu
1.c:15:31: warning: format specifies type 'int' but the argument has type
'unsigned long' [-Wformat]
printf("size of char is %d\n",sizeof(char));
~~ ^~~~~~~~~~~~
%lu
1.c:16:28: warning: format specifies type 'int' but the argument has type
'unsigned long' [-Wformat]
printf("size of k is %d\n",sizeof k);
~~ ^~~~~~~~
%lu
3 warnings generated.
我这里没有问题,建议用 Dev - C++ 进行编译,Dev - C++ 下载地址:https://sm.myapp.com/original/Development/Dev-Cpp_5.11_TDM-GCC_4.9.2_Setup.exe 代码是:#include <stdio.h>
int main() {
int i;
char j;
float k;
i = 123;
j = 'c';
k = 3.14;
printf("size of int is %d\n", sizeof(int));
printf("size of char is %d\n", sizeof(char));
printf("size of k is %d\n", sizeof k);
return 0;
} 应该是编译器的原因,你这个代码只是有一些可以忽略的小问题,
帮你改了改
#include <stdio.h>
int main(){
int i;
char j;
float k;
i = 123;
j = 'c';
k = 3.14f;
printf("size of int is %d\n", (int)sizeof(int));
printf("size of char is %d\n", (int)sizeof(char));
printf("size of k is %d\n", (int)sizeof (k));
return 0;
}
这样应该就不会报错了。
这不是错误。是三个警告,这个没啥问题
warning是警告,error才是错误
这个警告可以不消除,不影响执行,但是若想消除也是可以的。
warning中已经给出了警告的原因,sizeof的返回值是unsigned long类型,格式化应该用%lu,而你用的是%d。
你将三个%d都改为%lu即可。
#include <stdio.h>
int main() {
int i;
char j;
float k;
i = 123;
j = 'c';
k = 3.14;
printf("size of int is %lu\n", sizeof(int));
printf("size of char is %lu\n", sizeof(char));
printf("size of k is %lu\n", sizeof k);
return 0;
} #include <stdio.h>
int main()
{
int i;
char j;
double k;
i = 123;
j = 'c';
k = 3.14;
printf("size of int is %d\n",sizeof(int));
printf("size of char is %d\n",sizeof(char));
printf("size of k is %d\n",sizeof k);
return 0;
}
将 float 型改为 double 型,告警提示就没有了,运行的结果是:
size of int is 4
size of char is 1
size of k is 8
Press any key to continue
页:
[1]