本人大二狗,学过一点C基础,最近在学C艹,偶然看到大数相乘问题,想试试,于是写出了下面的代码。
#include<iostream>
#include<cstring>
#include<fstream>
void Multiply(char* str1, char* str2, char* Result);//相乘函数
void strRev(char* str);//字符串Reverse函数
void str2int(char* str);//将char - '0' 得到其代表的数值
void Carry(char* str); //计算进位函数
void int2str(char* str); //将所数值转换回 char
#define debug
int main()
{
#ifdef debug
std::ifstream in("Pr4_in.txt");
std::ofstream out("Pr4_out.txt");
std::cin.rdbuf(in.rdbuf());
std::cout.rdbuf(out.rdbuf());
#endif // debug
char Number_1[102], Number_2[102], Result[204]={'0'};
std::cin >> Number_1 >> Number_2;
Multiply(Number_1, Number_2, Result);
// std::cout << Number_1 << std::endl << Number_2 << std::endl;
std::cout << Result << std::endl;
return 0;
}
void Multiply(char str1[], char str2[], char Result[])
{
int len1 = strlen(str1), len2 = strlen(str2); //Get the length.
strRev(str1); strRev(str2); //Reverse the string.
//Simulate the manual computing process;
str2int(str1); str2int(str2);
//Initiate the result.
for(int i=0; i<203; ++i)
Result[i] = '*';
Result[203] = 0;
for(int i=0; i<len1; ++i){
for(int j=0; j<len2; ++j){
int tmp= (int)str1[i] * (int)str2[j];
if(Result[i+j] != '*')
Result[i+j] += tmp;
else Result[i+j] = tmp;
// if(tmp < 10){
// Result[i+j] += tmp;
// Carry(Result);
// }
// else{
// int teens = tmp/10;
// tmp %= tmp;
// Result[i+j+1] += teens;
// Carry(Result);
// }
Carry(Result);
}
}
int2str(Result);
strRev(Result);
}
void strRev(char* str)
{
int low = 0, high = strlen(str) - 1;
while(low < high)
{
char tmp = str[low];
str[low] = str[high];
str[high] = tmp;
++low; --high;
}
}
void str2int(char* str)
{
int len = strlen(str);
for(int i=0; i < len; ++i){
str[i] -= '0';
}
}
void Carry(char* str)
{
int i=0;
while(str[i]){
if( str[i] >= 10 ){
int tmp = str[i];
str[i] = tmp % 10;
str[i+1] += tmp / 10;
}
++i;
}
}
void int2str(char* str)
{
int i = 0;
while(str[i] != '*'){
str[i] += '0';
++i;
}
str[i] = '\0';
}
本人所用IDE: Code::Blocks, Compiler: g++;
所出现的问题:
输出空串。