I am trying to convert two char numbers into float, but I am not getting the correct result.
char firstnumber = '1';
char secondnumber = '2';
float sum ;
sum = ((firstnumber - '0') /(secondnumber - '0'));
cout << sum;
The output is always 0 , rather than 0.5 , please enlighten me.
You're doing integer division, which truncates the result. You need to add a typecast to get at least one of the /
operands to be a floating point number.
sum = (float)(firstnumber - '0') / (secondnumber - '0');
When you divide two integers, you get integer division. You want:
sum = (firstnumber - '0');
sum /= (secondnumber - '0');
(Or some other way of accomplishing the same thing.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.