有问题的代码:
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
double m;
cin >> m;
int L = 3, AAA;
int Q=0;
AAA = m;
cout<<AAA<<endl;;
Q = (AAA % 10)*pow(10, L - 1);
cout<<pow(10,L-1)<<endl;
cout<<AAA%10<<endl;
cout<<Q << endl;
return 0;
}
截图
原因是pow的double的返回值,在浮点计算中会产生精度的偏差,而这个偏差在VC和VS中不会发生,是在codeblocks中发现的,注意
方法是将Q改为double
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
double m;
cin >> m;
int L = 3, AAA;
double Q=0;
AAA = m;
cout<<AAA<<endl;;
Q = (AAA % 10)*pow(10, L - 1);
cout<<pow(10,L-1)<<endl;
cout<<AAA%10<<endl;
cout<<Q << endl;
return 0;
}
本文讨论了在使用C++的math库函数pow()时遇到的精度丢失问题,特别是在涉及到浮点数计算时。代码示例展示了在不同编译器环境下,如CodeBlocks中可能出现的精度偏差。解决方法是将变量Q声明为double类型,以避免因类型转换导致的精度损失。
1万+

被折叠的 条评论
为什么被折叠?



