C程序求斜边,发现斜边太大

标签 c hypotenuse

这是我用 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。

这两个角色看起来非常相似。因此,还建议避免命名变量 llll1 等。

说明符%1f尝试将流中最多1个字节转换为 float ,并将结果存储到地址被传递的float中。您传递了一个double的地址,因此行为是未定义的。 您可以通过提高警告级别来防止这种愚蠢的错误:

  • gcc -Wall -Wextra -Werror
  • clang -Weverything -Werror
  • cl/W3cl/W4cl/Wall

关于C程序求斜边,发现斜边太大,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46010139/

相关文章:

计算斜边的 C 程序

C++ 创建绘制斜边的函数 - 三角函数

math - 如何仅使用斜边求直角三角形的反正切?

c - 访问 C 文件中的结构体

actionscript-3 - 三角三角学 (ActionScript 3)

c++ - Linux中mremap函数的特点

c - Arduino 和 Windows 串行通信问题?

c - valgrind 需要很长时间才能发现内存泄漏,但程序在没有 valgrind 的情况下运行需要几秒钟

c - 如何在没有分支的情况下实现二维环面