C++循环乘法程序输出不符预期,请求错误排查
C++按列自乘程序输出错误排查
问题说明
需要编写一个接受行数输入、按列进行自乘运算的C++程序,当输入行数为3时,预期输出:
3 9 27 9 27 81 27 81 243
但实际运行输入3后,输出结果为:
Enter number of rows: 3 3 9 27 81 243 729 2187 6561 19683
原代码
#include <iostream> using namespace std; int main() { int rows; cout << "Enter number of rows: "; cin >> rows; int i, j; int num = 1; int plc = 1; for(i = 1; i <= rows; i++) { for(j = 1 ; j<=rows ; j++) { plc = plc * rows; cout << plc << " "; } cout << endl; } return 0; }
错误原因
- 变量累积未重置:
plc变量仅初始化一次,每轮循环持续累积乘以rows,导致后续行的计算完全偏离预期。比如第一行结束时plc为27,第二行直接从27开始乘3,得到81、243等不符合要求的数值。 - 逻辑不符合预期规律:预期每一行第
j列的数值是rows的(i+j-1)次方(i为行号,j为列号),原代码未按行重置起始值,而是延续上一行的最终结果计算。
修正后的代码
#include <iostream> using namespace std; int main() { int rows; cout << "Enter number of rows: "; cin >> rows; for(int i = 1; i <= rows; i++) { // 计算当前行的起始值:rows的i次方 int current_val = 1; for(int k = 0; k < i; k++){ current_val *= rows; } // 输出当前行的所有列,每列依次乘以rows for(int j = 1; j <= rows; j++) { cout << current_val << "\t"; current_val *= rows; } cout << endl; } return 0; }
运行输入3后,输出将与预期一致:
Enter number of rows: 3 3 9 27 9 27 81 27 81 243
内容的提问来源于stack exchange,提问作者woofMaranon
相关产品推荐
相关产品推荐

