//大数据相乘,具体的算法思想见c #define _CRT_SECURE_NO_WARNINGS //vs2013去掉安全检查 #include <stdlib.h> #include <string.h> #include <iostream> using namespace std; class big_data { public: void init_string() { cout << "str1 = "; cin >> str1; cout << endl; cout << "str2 = "; cin >> str2; cout << endl; } char* big_data_multi () { int length_str1 = strlen(str1); int length_str2 = strlen(str2); int *pstr3 = (int*)malloc(sizeof(int)*(length_str1+length_str2)); memset(pstr3, 0, sizeof(int)*(length_str1+length_str2));//一定要初始化,否则乱码 for(int i = 0; i < length_str2; i++)//循环累乘相加 { for(int j = 0; j < length_str1; j++) { pstr3[i + j + 1] += (str1[j] - ‘0‘) * (str2[i] - ‘0‘); } } for (int i = length_str1 + length_str2 - 1; i >= 0; i--) { if(pstr3[i] >= 10) { pstr3[i - 1] += pstr3[i] / 10; pstr3[i] = pstr3[i]%10; } } int i = 0; while (pstr3[i] == 0) { i++; } char *pstr4 = (char*)malloc(sizeof(char)*(length_str1 + length_str2 + 1)); int j = 0; for(; j < length_str1+length_str2 && i < length_str1+length_str2; j++,i++) { pstr4[j] = pstr3[i] + ‘0‘; } pstr4[j] = ‘\0‘; return pstr4; } private: char str1[100]; char str2[100]; }; int main() { big_data bigdata1; while(1) { cout << endl; bigdata1.init_string(); cout << "相乘的结果是 :" << bigdata1.big_data_multi() << endl; } system("pause"); }
时间: 2024-10-03 21:47:24