首页 > 解决方案 > 为什么我得到 -0 而不是 0?

问题描述

我在 c 中编写了一个代码,它让我以三元组的形式逐个角度旋转点。
当我编译并运行测试用例时,它给我的输出为 -0,7 。
与 python 中的相同代码一样,我的输出为 0,7 。当我在在线编译平台上运行相同的代码时,它会给我正确的输出。
我正在使用代码块 Windows 10 操作系统。
代码块有问题吗?
我该怎么办?

C代码:

#include<stdio.h>
#include<math.h>
int main()
{
    double xp,yp,xq,yq,a,b,c;
    double t,xn,yn;
    int z;
    scanf("%d",&z);
  //  printf("Enter coordinates of p \n");
    scanf("%lf%lf",&xp,&yp);
   // printf("\nEnter triple \n");
    scanf("%lf%lf%lf",&a,&b,&c);
   // printf("\nEnter coordinates of q \n");
    scanf("%lf%lf",&xq,&yq);
    t=asin(b/c);
    if(z==0)
    {
    xn=xp*cos(t)-yp*sin(t)-xq*cos(t)+yq*sin(t)+xq;
    yn=xp*sin(t)+yp*cos(t)-xq*sin(t)-yq*cos(t)+yq;
    }
    else
    {
    xn=xp*cos(t)+yp*sin(t)-xq*cos(t)-yq*sin(t)+xq;
    yn=-xp*sin(t)+yp*cos(t)+xq*sin(t)-yq*cos(t)+yq;
    }
    printf("%lf     %lf",xn,yn);
    return 0;
}

输出:

0
4 7
3 4 5
2 3
-0.000000     7.000000
Process returned 0 (0x0)   execution time : 10.675 s
Press any key to continue.

https://stackoverflow.com/questions/34088742/what-is-the-purpose-of-having-both-positive-and-negative-zero-0-also-written

标签: c

解决方案


这里最有可能的是您实际上没有签名-0.0,但您的格式以这种方式呈现给您。

如果您的一个计算产生一个四舍五入为零的负次正规数,您将在浮点中得到一个带符号的负零。

如果您确实有一个纯有符号零,那么一种解决方法是使用三元条件运算符来破坏它,因为printf保留将有符号零传播到输出中的权利:f == 0.0 ? 0.0 : f是一种这样的方案,或者甚至使用更闪光但混淆的f ? f : 0.0. C 标准定义 -0.0为等于0.0。另一种方法(确认@EricPostpischil)是增加0.0价值。


推荐阅读