dxy19213987956 @ 2023-06-09 12:17:39
#include <iostream>
using namespace std;
int m[1005]={1},res[1005]={1},len=1004;
int n;
void f();
void solve()
{
int tmp;
for(int i=2;i<=n;i++)
{
for(int j=0;j<1004;j++)
{
int c=m[j]*i;
m[j]=(c+tmp)%10;
tmp=(c+tmp)/10;
}
f();
}
for(;res[len]==0;len--);
for(;len>-1;len--)cout << res[len];
}
void f()
{
int tmp;
for(int i=0;i<1004;i++)
{
res[i]=res[i]+m[i]+tmp;
tmp=res[i]/10;
res[i]=res[i]%10;
}
}
int main()
{
cin >> n;
solve();
}
by lihefan @ 2023-06-09 12:19:17
@dxy19213987956 这是一个计算阶乘的程序,但是存在一些问题,比如数组越界、没有考虑到0的情况等。下面是改进后的代码:
#include <iostream>
#include <cstring>
using namespace std;
const int MAXN = 1005;
int m[MAXN] = {1}, res[MAXN] = {1};
int len = 1;
void multiply(int x) {
int carry = 0;
for (int i = 0; i < len; i++) {
int t = m[i] * x + carry;
m[i] = t % 10;
carry = t / 10;
}
while (carry) {
m[len++] = carry % 10;
carry /= 10;
}
}
void add() {
int carry = 0;
for (int i = 0; i < len; i++) {
int t = res[i] + m[i] + carry;
res[i] = t % 10;
carry = t / 10;
}
while (carry) {
res[len++] = carry % 10;
carry /= 10;
}
}
void solve(int n) {
for (int i = 2; i <= n; i++) {
multiply(i);
add();
}
}
int main() {
int n;
cin >> n;
solve(n);
for (int i = len - 1; i >= 0; i--) {
cout << res[i];
}
cout << endl;
return 0;
}
改进后的代码使用了函数来分别计算乘法和加法,避免了数组越界的问题。同时,将数组长度 len 初始化为 1,避免了没有考虑到 0 的情况。最后,输出结果时从高位到低位输出,避免了输出前导零的问题。
by DreamLand_zcb @ 2023-06-09 12:22:52
@lihefan 盲猜GPT(
by lihefan @ 2023-06-09 12:24:51
是的,真聪明
by lihefan @ 2023-06-09 12:25:04
@DreamLand_zcb
by Vocaloid世末歌者 @ 2023-06-09 13:56:30
@DreamLand_zcb 我也猜gpt(((