bigint 프로젝트를하고 있는데, 왜 내 곱셈 연산자가 테스트 케이스에서 제대로 작동하지 않는지 잘 모르겠다.Bigint * operator
아마 불필요하기 때문에 .h 파일을 제외 시켰습니다.
bigint.cpp :
// Definition of multiplication operator
BigInt BigInt::operator*(BigInt addend2)
{
BigInt product;
short int first, // a block of 1st addend (this object)
second, // a block of 2nd addend (addend2)
result, // a block in their sum
carry = 0; // the carry in adding two blocks
list<short int>::reverse_iterator // to iterate right to left
it1 = myList.rbegin(), // through 1st list, and
it2 = addend2.myList.rbegin(); // through 2nd list
while (it1 != myList.rend() || it2 != addend2.myList.rend())
{
if (it1 != myList.rend())
{
first = *it1;
it1++ ;
}
else
first = 0;
if (it2 != addend2.myList.rend())
{
second = *it2;
it2++ ;
}
else
second = 0;
short int temp = first * second;
result = temp % 1000;
carry = temp/1000;
product.myList.push_front(result);
}
if (carry > 0)
product.myList.push_front(carry);
return product;
}
하여 Main.cpp (테스트 케이스) : 나는이 코드를 실행하면
int main()
{
char response;
do
{
cout << "\nMultiplication part:" << endl;
cout << "The multiplication of\n\t"
<< number1 << " * " << number2
<< "\nis\n\t" << number1 * number2 << endl;
cout << "\nAdd more integers (Y or N)? ";
cin >> response;
}
, 곱셈은 잘못된 것입니다.
다음은 샘플 실행입니다. 123 * 423의 곱셈은 분명히 올바르지 않은 -507입니다.
나는 곱셈의 정의를 엉망으로 만들었지 만 누군가 내가 엉망진창을 말할 수 있을까?
편집 : 내 코드가 컴파일되지만 제품이 잘못된 경우가 있습니다. 또한 짧은 int를 모두 long int로 변경합니다. 예를 들어
:
978 *
을 정확하지만 더 큰 숫자를 사용할 때 다음 문제가 발생 878 = 858,684.
예 : 올바르지
432,454 765,534 * = 330,722,436. 정답은 3.32 * 10^11
테스트 케이스에서 제외 된 작은 부분이 있습니다 – Josh
longs 또는 더 큰 유형을 사용해보십시오. 당신이 원하는 정도에 따라 푸리에 (fourier) 방법이나 톰 요리와 같은 큰 int 곱셈 알고리즘을 사용하기 시작할 수도 있습니다. –
짧은 정수를 long int로 변경하려고 시도했지만 도움이되지 않습니다. – Josh