问题描述
- C++初学者遇到的严重问题
-
#includeusing namespace std;int main() { double x = 10.7332; long a = x; double y = x - a; for (; y != 0;) { x *= 10; a = x; cout << a << endl << x << endl; y = x - a; cout << y << endl; } cout << "end"; return 0;}//结果为死循环,永远不输出end字符
//经调试发现当double=107332时,long=107331
//求教!
解决方案
你好好看下书,long是什么类型的,实在不行你就输出来结,一看你就知道了,书上都有
解决方案二:
输出结果:
107 107.332000
0.332000
1073 1073.320000
0.320000
10733 10733.200000
0.200000
107331 107332.000000
1.000000
1073319 1073320.000000
1.000000
10733199 10733200.000000
1.000000
107331999 107332000.000000
1.000000
1073319999 1073320000.000000
1.000000
10733199999 10733199999.999998
0.999998
107331999999 107331999999.999985
0.999985
1073319999999 1073319999999.999878
0.999878
10733199999999 10733199999999.998047
0.998047
107331999999999 107331999999999.984375
0.984375
1073319999999999 1073319999999999.875000
0.875000
10733199999999998 10733199999999998.000000
0.000000
解决方案三:
输出结果:
107 107.332000
0.332000
1073 1073.320000
0.320000
10733 10733.200000
0.200000
107331 107332.000000
1.000000
1073319 1073320.000000
1.000000
10733199 10733200.000000
1.000000
107331999 107332000.000000
1.000000
1073319999 1073320000.000000
1.000000
10733199999 10733199999.999998
0.999998
107331999999 107331999999.999985
0.999985
1073319999999 1073319999999.999878
0.999878
10733199999999 10733199999999.998047
0.998047
107331999999999 107331999999999.984375
0.984375
1073319999999999 1073319999999999.875000
0.875000
10733199999999998 10733199999999998.000000
0.000000
解决方案四:
for (; y != 0;)这句话有问题,y为double类型的,这个条件永远为真,所以是死循环,你可以换成for(; y > 0.000000001 && y <-0.000000001)试试看
解决方案五:
for (; y != 0;)这句话有问题,y为double类型的,这个条件永远为真,所以是死循环,你可以换成for(; y > 0.000000001 && y <-0.000000001;)试试看
解决方案六:
建议你学习一下各种数据类型与0的比较,,林悦的高质量C、C++编程指南的附录面试题里面说的有
解决方案七:
#if 1
#include
using namespace std;
int main()
{
double x = 10.7332;
long a = x;
double y = x - a;
//死循环,Y永远都是0.31999999,建议调试代码,记录并跟踪每一条语句执行后的变量的值
for (; y != 0;)
{
x *= 10;
a = x;
cout << a << endl << x << endl;
y = x - a;
cout << y << endl;
}
cout << "end";
return 0;
}
#endif