fork download
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <string>
  4.  
  5. using namespace std;
  6.  
  7. void printMultiplicationTable(int n) {
  8. if (n <= 0) return; // 处理非正整数的情况
  9.  
  10. int max_num = n * n;
  11. int max_width = to_string(max_num).size();
  12.  
  13. for (int i = 1; i <= n; ++i) {
  14. for (int j = 1; j <= n; ++j) {
  15. cout << setw(max_width) << i * j;
  16. if (j != n) {
  17. cout << " ";
  18. }
  19. }
  20. cout << endl;
  21. }
  22. }
  23.  
  24. // 示例用法
  25. int main() {
  26. printMultiplicationTable(5);
  27. return 0;
  28. }
Success #stdin #stdout 0.01s 5292KB
stdin
printMultiplicationTable(5);
stdout
 1  2  3  4  5
 2  4  6  8 10
 3  6  9 12 15
 4  8 12 16 20
 5 10 15 20 25