【发布时间】:2018-06-16 18:03:44
【问题描述】:
如果此代码中存在愚蠢的错误,我提前道歉,但我似乎无法解决它。我的问题是,我用 GCC-8 编译(通过 home-brew 安装在 Mac 上),然后在终端中执行。当使用 int 定义变量 s & a 时,我使用下面的打印语句得到零作为输出。如果我将 s & a 变量声明为 double 我仍然会在前两个打印语句中得到零,在最后一个打印语句中得到 1024。我只是不知道发生了什么。感谢任何帮助!
/* square code */
#include <stdio.h>
int main() {
int s, a;
printf("enter the length of your square \n");
scanf("%f", &s);
a= s * s;
printf("the area of your square is %f cm using f placeholder \n", a);
printf("the area of your square is %lf cm uning fl placeholder\n", a);
printf("the area of your square is %d cm using d placeholder \n", a);
return(0);
}
【问题讨论】:
-
int a无法成功传递给printf,其中预计double,无需强制转换。与scanf类似,应该是scanf("%d", &s);,并且没有强制转换可以解决这个问题。 -
如果你回到你的课本或讲义或教程,那么我敢肯定它会说一些类似于
"%f"格式的内容,scanf是用于@ 987654331@ 类型。格式和参数类型不匹配导致undefined behavior。 -
int s, a; .... scanf("%f", &s);会在警告完全启用时对许多好的编译器产生警告。节省时间并启用所有警告。