user11886585
user11886585

Reputation:

How do I calculate the sum in-between two negative integers c++

I have created a funktion that should be able to calculate addition, multiplication and the square-root in-between 2 integers (both positive and negative). However, my code only works for positive integers.

For instance if I insert 3 and 5 it will calculate (3)+(4)+(5) = 12, but if I put in -3 and -5 the answer will be 0. The same thing happens if I put in 5 as my first integer and then 3 as my second, instead of 3 first and then 5. I can't figure out what's wrong with my code. I'd really appreciate some guidance and help with my problem!

int calculate(int num1, int num2, char op) {
  int answer, x;

  if (op == 'a') {
    answer = 0;
    for (x = num1; x <= num2; x++) {
      answer += x;
    }
  }

  if (op == 'm') {
    answer = num1;
    for (x = num1 + 1; x <= num2; x++) {
      answer = answer * (x);
    }

    if (op == 's') {
      answer = 0;
      for (x = num1; x <= num2; x++) {
        answer = answer + (x * x);
      }
    }
  }
  return answer;
}

Upvotes: 0

Views: 781

Answers (2)

DarenW
DarenW

Reputation: 16906

Depending on the values of the two given integers, you may have to go up or go down when looping. Instead of incrementing, you need to increment or decrement as needed, based on the sign of num2-num1.

Replace

for (x = num1; x <= num2; x++)

with

for (x = num1; x <= num2; x+=sign(num2-num1))

Oh, but is there a sign() function in C or C++? It should return -1, 0 or +1 depending on its one argument being <0, 0, or >0.

See: Is there a standard sign function (signum, sgn) in C/C++? and https://helloacm.com/how-to-implement-the-sgn-function-in-c/

Upvotes: 0

Alecto
Alecto

Reputation: 10740

The simplest way to do this is to add a line at the beginning of the function that swaps the two inputs, so that the smaller one always comes first:

#include <utility> // std::swap is in utility

int calculate(int num1, int num2, char op) { 
    if(num1 > num2) {
        std::swap(num1, num2); 
    }

    int answer = 0;

    if (op == 'a') {
        for (int x = num1; x <= num2; x++) {
            answer += x;
        }
    }

    if (op == 'm') { 
        answer = num1;
        for (int x = num1 + 1; x <= num2; x++) {
            answer = answer * x;
        }
    }

    if (op == 's') {
        for (int x = num1; x <= num2; x++){
            answer = answer + x*x;
        }
    }
    return answer;
}

Upvotes: 5

Related Questions