Thinerox Thinerox - 1 year ago 75
C++ Question

How to get the decimal result of two integers division?

So I have a burning question, I'm trying to divide two integers that are set with scanf, but I keep getting the answer 0.

int a, b, calculate;
printf("set a: ");
scanf("%d", a);
printf("set b: ");
scanf("%d", &b);
calculate = a / b;
printf("Answer: %d", calculate);

Can anyone help me with this? This isn't the code, its an example :3

Answer Source

Careful: You are dividing integers, not foating point values.

So if you divide two integers, say 4 and 5, the result will be zero and not 0.8 as you might expect. If you need floating point results, use floating point types as operands of the division and for the result.

It is usually sufficient to cast at least one of the operands (a and b) to float, but let's do it with both:

int a, b;
printf("set a: ");
scanf("%d", &a);
printf("set b: ");
scanf("%d", &b);
float calculate = (float) a / (float) b;
printf("Answer: %f", calculate);

Since the question is tagged as C++, but you actually use C-style input and output functions, you might as well change that. It's easier (at least in my opinion) and you do not have to remember the format specifiers for scanf and printf. So the same in C++ would be:

#include <iostream>
// ...
int a, b;
std::cout << "set a: ";
std::cin >> a;
std::cout << "set b: ";
std::cin >> b;
float calculate = static_cast<float>(a) / static_cast<float>(b);
std::cout << "Answer: " << calculate << std::endl;

(Added bonus: The static_cast keyword is also more self-explanatory about what is going on there, and it is easier to search for that than for C-style casts.)