gpt4 book ai didi

c - 不同倍数的错误输出

转载 作者:行者123 更新时间:2023-11-30 16:11:39 26 4
gpt4 key购买 nike

我正在创建一个简单的程序,它将检查角度的正弦和余弦值是否等于 1 我键入了此代码

#include <stdio.h>
#include <math.h>
int main()
{
int x;
printf("Enter the value of angle in degree: \n");
scanf("%d",&x);
double rad = 0.0174533*x;
double sum = pow(sin(rad),2) + pow(cos(rad),2);
printf("%f",sum);
if (sum == 1)
printf("\nsum of squares of sine and cosine is equal to 1");
else
printf("\nsum of squares of sine and cosine is not equal to

1"); 返回0;它说总和不等于 1,即执行 else block ,而如果我将代码更改为

#include <stdio.h>
#include <math.h>
int main()
{
int x;
printf("Enter the value of angle in degree: \n");
scanf("%d",&x);
double rad = angle*3.14/180;
double sum = pow(sin(rad),2) + pow(cos(rad),2);
printf("%f",sum);
if (sum == 1)
printf("\nsum of squares of sine and cosine is equal to 1");
else
printf("\nsum of squares of sine and cosine is not equal to 1");
return 0;

效果如何?

最佳答案

使用浮点运算计算角度的正弦和余弦平方和可能不会精确地产生 1,有两个原因:

  • 浮点运算仅近似于实际运算。由于浮点格式只能表示某些值,因此任何数学运算的实数结果都会四舍五入到浮点格式可表示的最接近的值。
  • 计算正弦、余弦和指数有点困难,sin 的实现, cos ,和pow例程可能有错误(大于浮点格式所需的错误)。

这些问题会导致算术错误。这些错误可能会也可能不会被抵消,因此最终结果可能会也可能不会是 1。

使用%f格式化 float 时,默认精度为小数点后六位。查看 1 和 double 中最接近 1 的可表示值之间的差异格式,小数点后需要16位。 (这假设 double 使用 IEEE-754 基本 64 位二进制格式,这很常见。)通常,您需要 17 个有效数字来唯一区分特定值。 (此数字由 DBL_DECIMAL_DIG 给出,在 <float.h> 中定义。)

如果您使用 printf("%.16f", sum); 格式化数字,您会看到差异。

虽然可以分析由舍入引起的变化,但它们的行为通常类似于随机波动。因此,所使用的算术的微小变化可能会导致不同的结果。在这种情况下, 0.0174533 之间的差异和3.14/180导致角度略有不同,从而导致计算结果略有不同。

关于c - 不同倍数的错误输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58556838/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com