C++阶乘计算问题:输出始终为0,total值每次均为0
阶乘计算结果始终为0的问题解决
你的问题核心是变量total没有初始化。C++里函数内的局部变量如果不手动赋值,会被分配随机的垃圾值,要是这个初始值是0,执行total *= a时不管乘多少次结果都会保持0。阶乘计算需要从1开始累乘,所以必须把total初始化为1。
另外尽量别用goto,代码可读性太差,用循环替代会更规范。下面是两种修正方案:
修正原goto版本代码
#include <iostream> using namespace std; int main() { int n, total = 1, a ; // 初始化total为1 cout << "enter number for factorial :"; cin >> n; a = n; top: if (a != 0) { total *= a; a -= 1; goto top; } cout << "factorial of " << n << " is " << total; }
更规范的while循环版本
#include <iostream> using namespace std; int main() { int n; long long total = 1; // 用long long避免大数值溢出 cout << "enter number for factorial :"; cin >> n; int a = n; while (a > 0) { total *= a; a--; } cout << "factorial of " << n << " is " << total; }
额外提醒:如果输入的n比较大(比如超过12),int类型会因为数值溢出导致结果错误,改用long long类型能支持更大的阶乘计算(最多到20!左右)。
内容的提问来源于stack exchange,提问作者chester Thapa
相关产品推荐
相关产品推荐

