1.用while循环实现:

#include <iostream>
using namespace std;

int main() {
    int n, i = 1, result = 1;
    cout << "请输入一个整数n:";
    cin >> n;
    while (i <= n && result > 0) {
        result *= i;
        i++;
    }
    if (result <= 0) {
        cout << "超出了int类型能表示的范围" << endl;
    }
    else {
        cout << n << "! = " << result << endl;
    }
    return 0;
}

2.用do_while循环实现:

#include <iostream>
using namespace std;

int main() {
    int n, i = 1, result = 1;
    cout << "请输入一个整数n:";
    cin >> n;
    do {
        result *= i;
        i++;
    } while (i <= n && result > 0);
    if (result <= 0) {
        cout << "超出了int类型能表示的范围" << endl;
    }
    else {
        cout << n << "! = " << result << endl;
    }
    return 0;
}

3.用for循环实现:

#include <iostream>
using namespace std;

int main() {
    int n, result = 1;
    cout << "请输入一个整数n:";
    cin >> n;
    for (int i = 1; i <= n && result > 0; i++) {
        result *= i;
    }
    if (result <= 0) {
        cout << "超出了int类型能表示的范围" << endl;
    }
    else {
        cout << n << "! = " << result << endl;
    }
    return 0;
}

对于int类型,其范围为-2147483648~2147483647,当计算阶乘时,如果超出了这个范围,会出现溢出的情况,即计算结果变成负数或者0。因此,在实际使用时,需要在计算前判断计算结果是否超出范围,如果超出了,可以使用其他数据类型,如long long或者double等。

1、分别用whiledo_while和for循环实现:输入一个整数n计算n!并输出计算结果。要求:1当阶乘为int型时测试n可以计算出有效结果的n的范围。2当阶乘超出上述范围时应如何处理才能使结果有效?

原文地址: https://www.cveoy.top/t/topic/bunx 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录