这是我在C中的第一个程序.当我运行它时,它发现的斜边是巨大的.我输入A和B作为2,输出为130899047838401965660347085857614698509581032940206478883553280.000000.我做错了什么?
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int die(const char *msg);
double hypotenuse(double side0, double side1);
int main()
{
double a, b, c;
printf("Enter side A: ");
if (scanf_s("%1f", &a) != 1)
die("input failure");
printf("Enter side B: ");
if (scanf_s("%1f", &b) != 1)
die("input failure");
c = hypotenuse(a, b);
printf("The hypotenuse is %f\n ", c);
}
int die(const char *msg)
{
printf("Fatal Error: %s\n", msg);
exit(1);
}
double hypotenuse(double side0, double side1)
{
return sqrt((side0 * side0) + (side1 * side1));
}
Run Code Online (Sandbox Code Playgroud)
scanf()转换说明符中有一个拼写错误:%1f应该%lf使用ell而不是one.
这两个字符看起来看似相似.出于这个原因,它也建议,以避免变量命名l或ll,l1等等.
说明符%1f尝试从流中最多转换1个字节作为浮点数,并将结果存储到float其地址传递的地址中.您传递了a的地址double,因此行为未定义.您可以通过提高警告级别来防止这种愚蠢的错误:
gcc -Wall -Wextra -Werrorclang -Weverything -Werrorcl /W3或cl /W4或cl /Wall