C++ 乘法运算竖式输出 - 代码示例
C++ 乘法运算竖式输出
本页面提供 C++ 代码示例,演示如何模拟乘法运算并以竖式形式输出结果。
题目描述
从键盘读入两个 1000 以内的正整数 m, n (n≤m),请你模拟乘法运算并以竖式形式输出。
输入
两个 1000 以内的正整数 m, n (n≤m),两数由一个空格分隔。
输出
输出两个整数进行乘法运算的竖式。每行数字右侧直接回车,没有空格了;最后一行的积所代表的数字左侧无任何内容。具体格式见下面的样例输出。
样例输入
12 3
样例输出
1 2
x 3
-----
3 6
1 2
-----
3 6
样例输入
123 45
样例输出
1 2 3
x 4 5
----------
5 8 5
4 9 2
---------
5 5 3 5
代码示例
#include <iostream>#include <string>using namespace std;
int main() { int m, n; cin >> m >> n;
string str1 = to_string(m), str2 = to_string(n); int len1 = str1.length(), len2 = str2.length();
// 打印第一个数 for (int i = 0; i < len1; i++) { cout << ' '; } cout << str1 << endl;
// 打印乘号 for (int i = 0; i < len1 - 1; i++) { cout << ' '; } cout << 'x'; for (int i = 0; i < len2; i++) { cout << ' '; } cout << str2 << endl;
// 打印分割线 for (int i = 0; i < len1 + len2; i++) { cout << '-'; } cout << endl;
// 模拟乘法竖式 int carry = 0; for (int i = len2 - 1; i >= 0; i--) { for (int j = len1 - 1; j >= 0; j--) { int product = (str1[j] - '0') * (str2[i] - '0') + carry; carry = product / 10; cout << product % 10; } cout << carry; carry = 0; if (i != 0) { for (int k = 0; k < len2 - i - 1; k++) { cout << ' '; } } cout << endl; }
// 打印分割线 for (int i = 0; i < len1 + len2; i++) { cout << '-'; } cout << endl;
// 打印积 int product = m * n; cout << product << endl;
return 0;}</code></pre><h2>运行结果</h2><p>用户输入 12 3,程序将输出:</p><pre><code> 1 2 x 3----- 3 61 2 -----3 6 </code></pre><p>用户输入 123 45,程序将输出:</p><pre><code> 1 2 3 x 4 5---------- 5 8 5 4 9 2 ---------5 5 3 5 </code></pre
原文地址: https://www.cveoy.top/t/topic/qaFo 著作权归作者所有。请勿转载和采集!