【发布时间】:2022-06-15 16:06:54
【问题描述】:
我有一个任务要求我编写一个程序,该程序将两个大数相乘,每个大数存储在一个最大长度为 100 的字符数组中。经过无数次的努力和调试,逐步将 10 位数字相乘手,我现在写了下面一段乱七八糟的代码:
#include <iostream>
#include <string.h>
using namespace std;
const int MAX_SIZE = 100;
int charToInt(char);
char IntToChar(int);
long long int pow10(int);
bool isNumber(char[]);
void fillWith0(char[], int);
void multiply(char[], char[], char[]);
int main(){
char first_num[MAX_SIZE + 1], second_num[MAX_SIZE + 1], product[2 * MAX_SIZE + 1];
cout << "A =\t";
cin.getline(first_num, MAX_SIZE);
cout << "B =\t";
cin.getline(second_num, MAX_SIZE);
multiply(first_num, second_num, product);
cout << "A * B = " << product << endl;
return 0;
}
int charToInt(char ch){
return ch - '0';
}
char intToChar(int i){
return i + '0';
}
long long int pow10(int pow){
int res = 1;
for (int i = 0; i < pow ; i++){
res *= 10;
}
return res;
}
bool isNumber(char input[]){
for (int i = 0; input[i] != '\0'; i++){
if (!(input[i] >= '0' && input[i] <= '9')){
return false;
}
}
return true;
}
void fillWith0(char input[], int size){
int i;
for (i = 0; i < size; i++){
input[i] = '0';
}
input[i] = '\0';
}
void multiply(char first[], char second[], char prod[]){
_strrev(first);
_strrev(second);
if (isNumber(first) && isNumber(second)){
fillWith0(prod, 2 * MAX_SIZE + 1);
int i, j, k;
long long int carry = 0;
for (i = 0; second[i] != '\0'; i++){
for (j = 0; first[j] != '\0'; j++){
long long int mult = (pow10(i) * charToInt(first[j]) * charToInt(second[i])) + carry + charToInt(prod[j]);
prod[j] = intToChar(mult % 10);
carry = mult / 10;
}
k = j;
while (carry != 0){
carry += charToInt(prod[k]);
prod[k] = intToChar(carry % 10);
carry = carry / 10;
k++;
}
}
prod[k] = '\0';
_strrev(first);
_strrev(second);
_strrev(prod);
}
}
我的问题是它不适用于超过 10 位的数字(1234567891 * 1987654321 可以正常工作,但没有更多的数字),因为在这些情况下的输出是一组奇怪的字符我认为是问题是某处溢出并导致奇怪的问题,尽管我使用long long int 来存储算法中仅有的两个数字整数,这样做帮助我从 6 位数字增加到 10 位,但仅此而已。有什么建议或可能的解决方案我可以实施吗?
附: :正如我之前提到的,这是一项作业,因此不允许使用库和其他东西,我已经看到使用向量实现了这一点,但不幸的是,我不能在这里使用向量。
提前谢谢你!
【问题讨论】:
-
如果这是 C++,你为什么不使用
std::string?或std::vector<char>?
标签: c++ arrays math largenumber