c++输出竖式计算
时间: 2023-07-01 12:24:33 浏览: 93
以下是一个简单的C++程序,可以输出两个数字的竖式计算结果:
```c++
#include <iostream>
#include <string>
using namespace std;
int main()
{
int num1, num2;
cout << "请输入两个数字:" << endl;
cin >> num1 >> num2;
// 将数字转换为字符串,方便输出
string str1 = to_string(num1);
string str2 = to_string(num2);
int len1 = str1.size();
int len2 = str2.size();
int len = max(len1, len2) + 1;
// 初始化结果数组,全部设置为0
int res[len] = {0};
// 逐位相乘,加到结果数组中
for (int i = 0; i < len1; i++) {
for (int j = 0; j < len2; j++) {
int mul_res = (str1[i] - '0') * (str2[j] - '0');
res[i+j] += mul_res % 10;
res[i+j+1] += mul_res / 10;
}
}
// 处理进位
for (int i = 0; i < len; i++) {
if (res[i] >= 10) {
res[i+1] += res[i] / 10;
res[i] %= 10;
}
}
// 去掉前导0
int i = len-1;
while (i > 0 && res[i] == 0) {
i--;
}
// 输出竖式计算结果
cout << str1 << " * " << str2 << " = " << endl;
for (; i >= 0; i--) {
cout << res[i];
}
cout << endl;
return 0;
}
```
这个程序采用了竖式计算的方法,先将输入的两个数字转换为字符串,然后逐位相乘,将结果加到一个数组中,最后处理进位,去掉前导0,输出结果。
相关推荐
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)