c - 为什么我得到 -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
解决方案
这里最有可能的是您实际上没有签名-0.0
,但您的格式以这种方式呈现给您。
如果您的一个计算产生一个四舍五入为零的负次正规数,您将在浮点中得到一个带符号的负零。
如果您确实有一个纯有符号零,那么一种解决方法是使用三元条件运算符来破坏它,因为printf
保留将有符号零传播到输出中的权利:f == 0.0 ? 0.0 : f
是一种这样的方案,或者甚至使用更闪光但混淆的f ? f : 0.0
. C 标准定义 -0.0
为等于0.0
。另一种方法(确认@EricPostpischil)是增加0.0
价值。
推荐阅读
- node.js - Yarn Create - npm 注册表似乎有问题
- visual-studio-code - Lua模块视觉工作室代码?
- react-native - Xcode 12 部署警告“IPHONEOS_DEPLOYMENT_TARGET”
- node.js - 会话属性在 React Express 应用程序中的请求中不会持续存在
- javascript - 如何使用 Nodejs 和 Typescript 从 Lambda 中的事件中获取 Cogntio 数据
- arm - 什么样的C代码可以编译成像“LDR R3,[R4,#0x18]”这样的汇编代码,其中R3是一个指针
- sql - SQL:如何获取每个月的总付款及其每月总计
- python - 如何在 Python 中检测字符串中的时间并将时间转换为不同的时区?
- php - 添加对原始列的引用?
- jenkins - Jenkins Ghprb 构建失败:错误:克隆远程 repo 'origin' 时出错