简体   繁体   中英

Performing operations on a double returns 0

I have a method that receives a number in a NSString format.

I wish to convert this string to a double which I can use to calculate a temperature.

Here's my method.

NSString *stringTemp = text; // text is a NSString 
NSLog(@"%@",stringTemp); // used for debugging
double tempDouble = [stringTemp doubleValue];
NSLog(@"%f",tempDouble); // used for debugging

Please note I put the NSLog commands here just to see if the number was correct. The latter NSLog returns a value of 82.000000 etc. (constantly changes as it's a temperature).


Next I wanted to use this double and convert it to a Celsius value. To do so, I did this:

double celsiusTemp = (5 / 9) * (tempDouble - 32);

Doing this: NSLog(@"%d", celsiusTemp); , or this: NSLog(@"%f", celsiusTemp); both give me a value of 0 in the console. Is there any reason why this would be happening? Have I made a stupid mistake somewhere?

Thank you for your help!

Try doing (5.0 / 9.0). If you only use an int to do math where you are expecting a double to be returned (like 0.55) everything after the decimal place will be lost because the cpu expects an int to be returned.

5 / 9 is the division of two integers, and as such uses integer division, which performs the division normally and then truncates the result. So the result of 5 / 9 is always the integer 0.

Try:

double celsiusTemp = (5.0 / 9) * (tempDouble - 32); 

If you evaulate (5/9) as an integer, then it is just 0.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM