#include <iostream>
usingnamespace 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;
}
@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.
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)