PDA

View Full Version : math operation




gonche1124
Oct 1, 2009, 04:18 PM
Hello,

I have two strings and I want to divide the length of each word and round up the result.
Can anyone help with this?

I've tried it with NSDecimalNumber but I get a bucnh of errors.

Thank you

Andres



kainjow
Oct 1, 2009, 05:42 PM
[str length] returns an int representing the number of characters. You can then divide it like any other number in C. The random() function can be used to round up a double.

If you still need help, post what code you're working with.

lee1210
Oct 1, 2009, 06:24 PM
The random() function can be used to round up a double.


I'm guessing you meant round(double), not random()... You'd probably get a very different result than you're hoping calling random.

-Lee

chown33
Oct 1, 2009, 06:41 PM
I've been rounding with random() for years. It keeps the testers on their toes. No comment about all those avionics and nuclear-plant control systems I helped write.

kainjow
Oct 1, 2009, 08:25 PM
I'm guessing you meant round(double), not random()... You'd probably get a very different result than you're hoping calling random.

-Lee

hehe oops, that is what I meant. Not sure why I put random :p

lloyddean
Oct 1, 2009, 09:45 PM
It's unclear what you're asking for but the closest seems to be rounding of real numbers to integers, so ...


#include <math.h>

double n;
float f;
double d;

n = 3.4;
f = floorf(n); // results = 3
d = floor(n); // results = 3
f = ceilf(n); // results = 4
d = ceil(n); // results = 4
f = roundf(n); // results = 3
d = round(n); // results = 3


n = 3.6;
f = floorf(n); // results = 3
d = floor(n); // results = 3
f = ceilf(n); // results = 4
d = ceil(n); // results = 4
f = roundf(n); // results = 4
d = round(n); // results = 4

gonche1124
Oct 2, 2009, 03:59 PM
It's unclear what you're asking for but the closest seems to be rounding of real numbers to integers, so ...


#include <math.h>

double n;
float f;
double d;

n = 3.4;
f = floorf(n); // results = 3
d = floor(n); // results = 3
f = ceilf(n); // results = 4
d = ceil(n); // results = 4
f = roundf(n); // results = 3
d = round(n); // results = 3


n = 3.6;
f = floorf(n); // results = 3
d = floor(n); // results = 3
f = ceilf(n); // results = 4
d = ceil(n); // results = 4
f = roundf(n); // results = 4
d = round(n); // results = 4


Thanks that was really helpfull!!!

jared_kipe
Oct 2, 2009, 04:40 PM
Just remember that you'll need to typecast the int that is returned by
-(NSUInteger) length;

such as

unsigned int test1, test2;
test1 = [@"test1 string" length]; // 12
test2 = [@"test2 string 1234" length]; // 17

double result;
result = (double)test1/test2; // ~0.7

NSLog(@"result = %0.2d", result); // prints "result = 0.71"
result = round(result);
NSLog(@"result = %0.2d", result); // prints "result = 1.00"




Just remember one thing, the round function rounds UP .6 and rounds DOWN .5 Unlike how you learned in elementary school.