这是我用 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));
}
最佳答案
您的 scanf()
转换说明符中存在拼写错误:%1f
应该是 %lf
,其中带有 ell 而不是 1。
这两个角色看起来非常相似。因此,还建议避免命名变量 l
或 ll
、l1
等。
说明符%1f
尝试将流中最多1个字节转换为 float ,并将结果存储到地址被传递的float
中。您传递了一个double
的地址,因此行为是未定义的。
您可以通过提高警告级别来防止这种愚蠢的错误:
gcc -Wall -Wextra -Werror
clang -Weverything -Werror
cl/W3
或cl/W4
或cl/Wall
关于C程序求斜边,发现斜边太大,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46010139/