cpp 程序中的意外输出
Unexpected output in cpp program
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
int temp = 0, n = 1100, x = 0, t2 = 0, l = 10;
while(temp < n)
{
t2 = temp;
temp += pow(l, ++x);
cout << t2 << " " << temp << " " << x <<endl;
}
return(0);
}
获得的输出是:
0 10 1
10 109 2
109 1109 3
但我希望输出:
0 10 1
10 110 2
110 1100 3
为什么这种差异?..请帮忙..我找不到问题
不要将 pow
用于整数算术。尝试
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
int temp = 0, n = 1100, x = 0, t2 = 0, l = 10;
while(temp < n)
{
t2 = temp;
int t3 = 1, t4 = 0;
++x;
while (t4++ < x) t3 *= l;
temp += t3;
cout << t2 << " " << temp << " " << x <<endl;
}
return(0);
}
// or alternatively
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
int temp = 0, n = 1100, x = 0, t2 = 0, l = 10;
while(temp < n)
{
t2 = temp;
temp += floor(pow(l, ++x) + .5);
cout << t2 << " " << temp << " " << x <<endl;
}
return(0);
}
默认情况下,pow 返回双精度。这意味着当您使用表达式temp += pow(l, ++x);
时,有一个从 double 到 int 的隐藏强制转换,以便匹配temp
的类型。
双精度没有确切的表示形式(如整数(。因此,100
的双精度值可以是类似 99.999999..99832
。将此值转换为 int 时,仅考虑小数点前的数字。因此,100
的相应值将99
。您可以通过添加一些非常小的值(如数学中的 epsilon(来纠正此问题:
while(temp < n)
{
t2 = temp;
double d = pow(l, ++x);
cout << (int) d << endl;
cout << (int) (d + 1e-10) << endl; // 1е-10 is 0.0000000001
temp += (int) (d + 1e-10);
}
相关文章:
- 字符串比较中的意外输出
- 来自 decltype 的意外输出类型
- 字符数组到十六进制字符串的转换 - 意外输出
- 使用 boost::regex 从目录中获取带有一些正则表达式的文件名称时出现意外输出
- 使用后序遍历递归的深度优先搜索会产生意外输出
- C++的意外输出
- 贝金纳C++练习解决方案的意外输出
- 无效* 转换获得意外输出
- 以下程序的意外输出
- 意外输出:矢量矢量(功率集)
- 基本 int 数组提供意外输出
- 线程的意外输出
- 减法中的意外输出
- 带有左移操作员C 的意外输出
- C strncpy意外输出
- 意外输出..函数绑定在虚拟表中的发生方式
- 星号的意外输出
- 已编译的 protobuf 文件的意外输出路径
- 打印对象矢量的意外输出
- 递归函数用于计算 n 个数字之和的意外输出