栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > C++面试题库

写一个方法1000 的阶乘。

写一个方法1000 的阶乘。

答:C++的代码实现如下:
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
class longint {
private:
vector<int> iv;
public:
longint(void) { iv.push_back(1); }
longint& multiply(const int &);
friend ostream& operator<<(ostream &, const longint &);
};
ostream& operator<<(ostream &os, const longint &v) {
vector<int>::const_reverse_iterator iv_iter = v.iv.rbegin();
os << *iv_iter++;
for ( ; iv_iter < v.iv.rend(); ++iv_iter) {
os << setfill(‘0’) << setw(4) << *iv_iter;
}
return os;
第52 页共59 页
}
longint& longint::multiply(const int &rv) {
vector<int>::iterator iv_iter = iv.begin();
int overflow = 0, product = 0;
for ( ; iv_iter < iv.end(); ++iv_iter) {
product = (*iv_iter) * rv;
product += overflow;
overflow = 0;
if (product > 10000) {
overflow = product / 10000;
product -= overflow * 10000;
}
iv_iter = product;
}
if (0 != overflow) {
iv.push_back(overflow);
}
return *this;
}
int main(int argc, char **argv) {
longint result;
int l = 0;
if(argc==1){
cout << “like: multiply 1000” << endl;
exit(0);
}
sscanf(argv[1], “%d”, &l);
for (int i = 2; i <= l; ++i) {
result.multiply(i);
}
cout << result << endl;
return 0;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/265993.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号