¿C++ redondea los números? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

¿C++ redondea los números?

La cuestión es que, si por ejemplo la variable 'a' tiene el valor del entero 11, la siguiente cuenta (a*50)/100 debería dar 5.5, sin embargo el resultado en el compilador C++ de SoloLearn y en Sublime Text es 5, Agradecería una explicación, y me gustaría saber cómo hacer que el resultado sea un decimal.

11th Jan 2021, 12:28 AM
Krys
Krys - avatar
1 Answer
+ 1
/* Integer arithmetic prints integer results. If you want decimals in the output then use floating point arithmetic. Below you can see a few ways to get decimal output. You can use a (float) cast. You can use floating point literals in the calculation. You can declare the variable as float type instead of int. */ #include <iostream> using namespace std; int main() { int a = 11; float b = 11; cout << "int a:" << endl; cout << (a*50)/100 << endl; //5 cout << (float)(a*50)/100 << endl; //5.5 cout << (a*50.0)/100 << endl; //5.5 cout << (a*50)/100.0 << endl; //5.5 cout << "float b:" << endl; cout << (b*50)/100 << endl; //5.5 return 0; }
11th Jan 2021, 2:23 AM
Brian
Brian - avatar