[英]multiplying two large numbers in C / C++
我試圖為此提出解決方案……兩個大數a
和b
用char[]
或char*
,目標是將它們乘以第三個指針char* c
:
void multiply( const char* a, const char* b ){
int len_a = strlen( a );
int len_b = strlen( b );
int* c = new int[ len_a + len_b];
memset( c, 0, sizeof(int) * ( len_a + len_b ));
for( int i = len_a - 1; i >= 0; i-- ){
for( int j = len_b - 1; j >= 0; j-- ){
c[ i + j + 1 ] += ( b[ j ] - '0') * ( a[ i ] - '0' );
}
}
for( int i = len_a + len_b; i >= 0; i-- ){
if( c[ i ] >= 10 ){
c[ i - 1 ] += c[ i ] / 10;
c[ i ] %= 10;
}
}
cout << a << " * " << b << " = " << c << endl;
delete[] c;
}
我編寫了上面的函數來為我執行此操作...但是,當我使用輸入時:
int main( void ){
const char* a = "999";
const char* b = "99999";
multiply( a, b );
// I expect the answer to be 1 and 6
// profit = 0.92
return 0;
}
我有:
999 * 99999 = 0x100100080
為什么我要獲取內存地址而不是實際編號? 謝謝!
因為c
是一個int指針,而cout的流運算符如果傳遞了這樣的指針,則會打印一個內存地址。 要獲得該值,您需要使用*c
取消引用指針。 您可能需要編寫一個循環以打印整數的整個“字符串”。
cout << a << " * " << b << " = ";
for( int i = 0; i < len_a + len_b; i++ ){
cout << c[ i ];
}
cout << endl;
將產生預期的結果...
您的邏輯是正確的。 謹此提醒您:創建整數指針並將其用作數組時,它指向“數組的第一個元素”,因此在打印時,您會看到數組c的第一個元素的地址,在您的情況下為“ 0x100100080”。
要打印存儲在c中的數字(字符),您需要取消引用指針,即,一個接一個地打印數組中的元素。 或者,您也可以將數組轉換為數字並立即打印。 對於后者,請參閱: 如何在C中將整數數組轉換為整數? 。 要一一打印字符,可以替換
std::cout<<c;
使用以下代碼:
int n=strlen(c);
for(int i=0; i<n; i++) {
std::cout<<c[i];
}
這將打印號碼。
std::ostream
(類型為std::cout
類型)沒有專門用於int*
重載運算符,因此它會退回到void*
重載,后者僅以實現定義的方式輸出指針值。
此外, int*
重載不可能確定指針指向一個數組,更進一步的是,該數組將具有多少個元素。
for(c ++ 14)我們可以使用boost libarary ..
#include <iostream>
#include <boost/multiprecision/cpp_int.hpp>
namespace mp = boost::multiprecision;
int main()
{
mp::cpp_int s1("12368123681263817263863821638126328136218362182");
mp::cpp_int s2("345897937325785470923092923709887329092470423707534025");
mp::cpp_int S=s1*s2;
std::cout << S << '\n';
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.