0
changing datatypes in C, C++
Hi, I can't find the solution, can any one help me? How to convert a variable from int to float or an other data type? int num1 = 10; I wan't to convert this to a float or a double so I can do this: float num2 = 5,5; num1 += num2; num1 is equal to 15,5 and of type float; Thanks
6 ответов
+ 4
Yes Robin Rademaker, that's right, there's no way to change a declared variable from one type into another in C/C++, because it's against the strongly typed language characteristic 👍
+ 3
Since you want the final value (sum of num1 + num2) to be a floating point type, you also need to use float for the final value. If you do `num1 += num2;` while num1 is an int you'll end up with 15 instead of 15.5, the fraction will be removed.
int num1 = 10;
float num2 = 5.5;
// The mix needs to be of the
// float type
float mix = (float)num1 + num2;
Hth, cmiiw
+ 3
Yes that's right Division by Zero, but since the OP (Original Poster) used int for num1 this would be the way : )
+ 1
Wouldn't it make more sense to just make num1 a float in that case?
+ 1
ok I get that but I din't find anywhere how to change the data type of a variable
So I'm thinking now that once declared as a int the variable stays an int.
Yes y can pas the value to another variable but y can't change the data type of the same variable right?
0
Use casting.
num1 += (int)num2