C++ division

Why doesn't integer operation give me a float?

1
2
3
4
5
6
7
8
9
10
  int n1 = 0; //integer
  int n2 = 0; //integer

  cin >> n1;
  cin >>n2;
 
  float z = n1 / n2; //integer?
  cout << z; //this should not be an integer

return 0;


output:

1
2
3
  365
  25
  14
Last edited on
Because that's not the way it works. You will need to cast:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
using namespace std;

int main()
{

	int n1 = 0; //integer
	int n2 = 0; //integer

	cin >> n1;
	cin >> n2;

	float z = static_cast<float>(n1) / n2; //C++ casting
	//or:
	z = (float)n1 / n2; //C way of casting
        
        //better idea to do:
        z = static_cast<float>(n1) / static_cast<float>(n2); //C++ casting
	//or:
	z = (float)n1 / (float)n2; //C way of casting

	cout << z; //this should not be an integer

	cin.ignore();
	cin.get();
	return 0;
}
Last edited on
I think OP is missing something more fundamental.

float z = 12;

z is a float. But if I

cout << z << endl;

I will see:

12


It's still a float.
closed account (E0p9LyTq)
Why doesn't integer operation give me a float?

Because of how C++ (and your compiler) stores the underlying data of variable types when your source code is converted into machine code.

Why not just declare all 3 variables as floats? That way you don't have to cast and you get your expected decimal output.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

int main()
{
   float n1 = 365;
   float n2 = 25;

   float z = n1 / n2;

   std::cout << z << "\n";

   return 0;
}
@sasauke, thanks for the suggestion. I forgot about casting. @FurryGuy, I know I could just use all floats, but I was trying to understand something more fundamental. @Duoas , I know 12 is a float, but 365/25 is not 14; it's 14.6.

I think between sasauke and FurryGuy I have my answer. If what I gather is correct, the computer does the operation with the integers and by default produces an integer ( int a / int b = int c). Presumably because the solution has to have some type. That is what it stores in z and that is why cout prints 14 not 14.6. Casting the inputs as floats has a similar effect to declaring them as floats. That being the compiler using floats to do the calculation resulting in a float (float a / float b = float c) and that is what is put into z.
Ah, that's where you are making the mistake.

365/25 is not 14.6. It is 14. (integer divided by integer is integer)

365.0/25.0 is 14.6. (float divided by float is float)
365.0/25 is 14.6. (float divided by integer is float)
365/25.0 is 14.6 (integer divided by float is float)

no floats in == no floats out


[edit]
http://www.cplusplus.com/faq/beginners/integer-division/
Last edited on
Topic archived. No new replies allowed.