#include <iostream>
#include <sstream>
#include <numeric>
#include <math.h>
using namespace std;
int64_t splitAdd(int64_t value) {
ostringstream intStream;
intStream << value;
string intString(intStream.str());
return accumulate(intString.begin(), intString.end(), 0) - (intString.size() * int64_t('0'));
}
int main(int argc, char *argv[]) {
int64_t maxPower = 50;
int64_t results[maxPower];
for (int64_t tuple = 0; tuple <= maxPower; tuple++) {
for(int64_t power = 0; power <= maxPower; power++) {
int64_t value = pow(tuple, power);
while (value > 9) {
value = splitAdd(value);
}
results[power] = value;
}
cout << tuple << endl;
for (int i = 0; i < maxPower; i++) {
cout << results[i] << ',';
}
cout << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
过了一会儿,我反复得到了值:-9223372036854775808.我也在Code Runner 2中运行它,不确定这是否会产生影响.
一个明显的错误是这样的:
int64_t maxPower = 50;
int64_t results[maxPower]; // <-- Not really legal, but let's pretend
//...
for (int64_t power = 0;
power <= maxPower; // <-- Look at the loop constraints
power++)
{
//....
}
results[power] = value; // <-- Buffer overrun
Run Code Online (Sandbox Code Playgroud)
从maxPower50开始,您正在访问超出界限的元素.这是未定义的行为
另外,要使代码合法C++,要么声明一个50的数组:
int64_t results[50];
Run Code Online (Sandbox Code Playgroud)
或宣布一个std::vector<int64_t>.
当您这样做at()而不是使用时[],您可以更好地了解您的程序如何中断.见这里使用std ::向量的活生生的例子.
至于"奇数",你在这里得到一个数字溢出:
int64_t value = pow(tuple, power);
Run Code Online (Sandbox Code Playgroud)
如果tuple是3,power则为41,则该值溢出该int64_t类型.
也许你需要使用一个任意精度库(最好是重载必需的数学运算符)或编写自己的精度库,而不是使用"常规"C++类型.那么你不会或不应该溢出.
| 归档时间: |
|
| 查看次数: |
3044 次 |
| 最近记录: |