-7

I know this question asked many times but I am facing different problem in my code, I try to calculate sum of long integers range between 2-15.

Code:

long array[20];
long NUMBERS;

cout << "How many numbers ? : ";
cin >> NUMBERS;
long sum=0;
for (int i = 0; i < NUMBERS;i++){

    cout << "Input number " << (i+1) << " : ";
    cin >> array[i];    
}

cout << "Calculate Sum" << endl;
for (int i = 0; i < NUMBERS;i++){
    sum = sum + array[i];
}

cout << "Sum is : " << sum << endl;

When I input these three numbers.

  1. 1234567
  2. 123456
  3. 12345

Output:

Sum is : 1370368

but actual answer is : 3703627.

I try these solutions summing-large-numbers and sum-of-alternate-elements-of-integer-array but still not get right solution, also how we can solve this problem if user input different number with different ranges.

Community
  • 1
  • 1
Omore
  • 614
  • 6
  • 18

3 Answers3

6

This isn't about programming, but math... Hope this helps: http://www.wikihow.com/Add-Large-Numbers

(As a simple example, add 1 and 11. What is the result? 12 or 21?)

inabout
  • 311
  • 2
  • 6
0

my code sum large number with string. first you enter number of numbers you want to sum(to 25). and then you enter the number (to 180 'each number').

#include <iostream>
#include <stdlib.h>
using namespace std;
int main (){
    int band;
    cin >> band;
    string string_of_number[25];
    for (int i=0; i<band; i++){ //for get all string number
        cin >> string_of_number[i];
    }
    int strings_length[band];
    for (int i=0; i<band; i++){ //for get all length of strings
        strings_length[i]=string_of_number[i].length();
    }
    int answer[180];
    for(int i=0; i<180; i++){
        answer[i]=0;
    }
    int remaner=0;
    int sum=0;
    int last=180;
    for (int h=0; h<band; h++){ // for sum strings with sum answer one by one
        int j=179;
        for (int i=strings_length[h]; i>=0; i--){
        if(string_of_number[h][i]=='\0'){
            i--;
        }
        sum = (remaner + (string_of_number[h][i]-'0') + answer[j]) %10;
        remaner = ((string_of_number[h][i]-'0') + answer[j]) / 10;
        answer[j]=sum;
        if (i==0 && remaner>0){
            j--;
            answer[j]+=remaner;
            remaner=0;
        }
        if(last>j)
            last=j;
            j--;
           }
          }
        for(; last<180; last++){
        cout << answer[last];
        } 
   }
-2

It seems that your program assumes all numbers are 7 digit:

1234567

123456[0]

12345[00]

Ali Asadpoor
  • 327
  • 1
  • 13