C程序求斜边,发现斜边太大
C Program to find hypotenuse, hypotenuse found too big
这是我用 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 而不是 one。
这 2 个字符看起来非常相似。为此,也建议避免命名变量l
或ll
、l1
等
说明符 %1f
尝试将流中最多 1 个字节转换为浮点数,并将结果存储到传递地址的 float
中。您传递了 double
的地址,因此行为未定义。
您可以通过提高警告级别来防止这种愚蠢的错误:
gcc -Wall -Wextra -Werror
clang -Weverything -Werror
cl /W3
或 cl /W4
或 cl /Wall
这是我用 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 而不是 one。
这 2 个字符看起来非常相似。为此,也建议避免命名变量l
或ll
、l1
等
说明符 %1f
尝试将流中最多 1 个字节转换为浮点数,并将结果存储到传递地址的 float
中。您传递了 double
的地址,因此行为未定义。
您可以通过提高警告级别来防止这种愚蠢的错误:
gcc -Wall -Wextra -Werror
clang -Weverything -Werror
cl /W3
或cl /W4
或cl /Wall