简体   繁体   中英

Math issue in C++

I am making a code in which you input two numbers, a and b, then it calculates how many b's can be inside a, and then it displays this number with the quantity that is left. Although when a=-2147483648 and b = 10 it does the math wrong, I can find out what is the issue, even with the debugger.Thank you!!

#include <iostream>
#include <cmath>
int main() {
    int multiple, a, b, rest;
    std::cin >> a >> b;
    if (a > 0)
    {
        multiple = floor(a / b);
        rest = a - (multiple * b);
    }
    else
    {
        multiple = floor((a - b) / b);
        rest = (multiple*b - a);
    }

    std::cout << multiple << " " << rest << std::endl;
}

Result espected -214748365 2 Result given 214748363 -18

You are expecting from program to give: (-16)/6 = -3 times 6 and + 2. But it does not work in this way on computer operators. It just divides 16 by 6 and at the end it puts minus so we get -4. I made a bit changes on your code to serve on your purpose. We gotta make a program to serve on the way you want. So because your multipler is minus when a < 0, we need to add (-1) to it. So 6*(multipler - 1) + 2 == 6*(-2-1)+2 == -16 so:

#include <iostream>
using namespace std;

int main()
{
    int multiple, a, b, rest;
    std::cin >> a >> b;
    if (a > 0)
    {
        multiple = a / b;
        rest = a - (multiple * b);
    }
    else
    {
        multiple = a / b - 1;
        rest = -(multiple*b - a);
    }

    std::cout << multiple << " " << rest << std::endl;

    return 0;
}

run:

./a.out 
-2147483648
10
-214748365 2
#include <iostream>
#include <cmath>
main (){
 double multiple, a, b, rest;
 std::cin >> a >> b;
 // you have to make sure b not equal zero 
 if (b != 0){
    // when a is bigger then many b's can be inside a 
    if (a > b){
       multiple = floor (a / b);
       rest = a - (multiple * b);
    }
    // when b is bigger then no b's can be inside a 
    else if (a < b){
             multiple = 0;
             rest = a;
    }
    // when a = b  then it only one b can be inside a 
    else{
          multiple = 1;
          rest = 0;
    }
  }
 std::cout << multiple << " " << rest << std::endl;

its all cases coverd to calculates how many b's can be inside a and you can try the % operator it will be better

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM