use*_*703 1 c++ arrays codeblocks
假设我们有从[0]到[14]的15个数字满足:
a[0]=4
a[i]=pow(sqrt(a[i-1])*2-1, 2) for i>=1 and i<=14
Run Code Online (Sandbox Code Playgroud)
我需要打印出从[0]到[14]的所有值,每个数字在一行上,所以我写下面的代码(C++,Code :: Blocks):
#include <iostream>
#include <cmath>
using namespace std;
#define maxN 15
int i[maxN]; int n=15;
int main()
{
i[0]=2;
cout<<4<<endl;
for (int k=1; k<n; k++){
i[k]=i[k-1]*2-1;
cout<<pow(i[k],2)<<"\t"<<endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
结果是:
4
9
25
81
289
1089
4225
16641
66049
263169
1.05062e+006
4.1984e+006
1.67854e+007
6.71252e+007
2.68468e+008
Run Code Online (Sandbox Code Playgroud)
最后五个数字不正确(因为整数溢出).
在上面的"for"循环中,我改变了这一行
cout<<pow(i[k],2)<<"\t"<<endl;
Run Code Online (Sandbox Code Playgroud)
至
cout<<(long) pow(i[k],2)<<"\t"<<endl;
Run Code Online (Sandbox Code Playgroud)
这一次,结果是:
4
9
24
81
289
1089
4224
16641
66048
263168
1050625
4198400
16785408
67125248
268468224
Run Code Online (Sandbox Code Playgroud)
手动检查后,我意识到许多数字仍然不正确:24; 4224; 66048; 263168; 4198400; 16785408; 67125248; 268468224(它们都比正确的数字低1).我该怎么做才能解决这个问题?
1.05062e + 006和1050625是相同的值,打印方式不同.pow(i[k],2)返回浮点类型,此处不会发生整数溢出,而是在将此类浮点转换为舍入时进行舍入long.
该格式Xe+Y称为科学记数法,其价值为X * 10 ^ Y.默认情况下,std::printf并std::ostream::operator<<打印浮点值超过他们的科学记数法一定的约束.有关详细信息,请参阅https://en.cppreference.com/w/cpp/io/manip/fixed.
我该怎么做才能解决这个问题?
更改
cout<<pow(i[k],2)<<"\t"<<endl;
Run Code Online (Sandbox Code Playgroud)
至
cout<<i[k]*i[k]<<"\t"<<endl;
Run Code Online (Sandbox Code Playgroud)
pow是一个浮点函数,可能是不精确的.请注意,在您的情况下有一些奇怪的事情:如果pow使用64位IEEE-754双打,它应该为您的输入打印准确的数字.所以也许你使用32位float数字.
| 归档时间: |
|
| 查看次数: |
106 次 |
| 最近记录: |