开发者

How to divide numbers and integers?

开发者 https://www.devze.com 2023-02-23 01:39 出处:网络
I\'m tryin开发者_运维问答g to divide 2 integers but the results returns zero no matter what. Should I use float or what? I just can\'t get it to work. I\'ve tried floats but I get weird results. Here\

I'm tryin开发者_运维问答g to divide 2 integers but the results returns zero no matter what. Should I use float or what? I just can't get it to work. I've tried floats but I get weird results. Here's my code:

    NSUInteger someNumber = 156;
    NSUInteger points = 597;
    NSUInteger otherNumber = 5;
    NSUInteger difference = (someNumber - points);
    NSLog(@"%d", difference);
    NSUInteger divide = (difference / otherNumber);
    NSLog(@"%d", divide);
    NSUInteger multiply = (divide * 4826);
    NSLog(@"%d", multiply);
    NSUInteger total = (358 - multiply);
    NSLog(@"%d", total);

Any help would be much appreciated, Thanks.


Integer division truncates. To divide the two integers i and j and get a decimal fraction, you might use one of these for simple expressions. Code more complex expressions with all the caution that floating-point arithmetic requires. (Among other things, guarding against division by zero, loss of precision, and overflow.)

r = (float) i / j;
r = (double) i / j;


NSUIntegers have a minimum value of 0. If you're expecting negative values, you should be using NSInteger.


Shot in the dark, try the string formatter %u instead.


I finally fixed it!!! I had to change difference to a float.

NSUInteger difference = (someNumber - points);

to

float difference = (someNumber - points);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号