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

3rd Feb 2019, 11:52 AM
Robin R.
Robin R. - avatar
6 odpowiedzi
+ 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 👍
3rd Feb 2019, 5:19 PM
Ipang
+ 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
3rd Feb 2019, 1:55 PM
Ipang
+ 3
Yes that's right Division by Zero, but since the OP (Original Poster) used int for num1 this would be the way : )
3rd Feb 2019, 2:05 PM
Ipang
+ 1
Wouldn't it make more sense to just make num1 a float in that case?
3rd Feb 2019, 1:59 PM
Division by Zero
+ 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?
3rd Feb 2019, 2:44 PM
Robin R.
Robin R. - avatar
0
Use casting. num1 += (int)num2
3rd Feb 2019, 11:58 AM
Division by Zero