How do you check if an NSInteger is greater than another NSinteger? - objective-c

I'm trying to write code that detects if an integer is greater than another integer. Is this possible?
Here is what i've done so far.
if (NumCorrect >> NumWrong) {
btnCool.title = #"Awww";
}
else {
btnCool.title = #"Cool!";
}
All its doing is going to the else
EDIT:
NSString *numCorrect = [NSString stringWithFormat:#"%d",NumCorrect];
NSString *numWrong = [NSString stringWithFormat:#"%d", NumWrong];
lblWrong.text = numWrong;
lblCorrect.text = numCorrect;
if (NumCorrect > NumWrong) {
btnCool.title = #"Awww";
} else {
btnCool.title = #"Cool!";
}

Use single >
if (NumCorrect > NumWrong) {
btnCool.title = #"Awww";
} else {
btnCool.title = #"Cool!";
}
Double >> is a bit shift operation. You shift every bit in the binary representation of your variable NumCorrect NumWrong amount of bytes to the right. In almost all cases this will return in a number other then 0, which will then treated as a false value and thus the else block is executed.

Almost perfect - just take off one of those >'s. >> and << are for "bit-shifting", a weird hold-over from the earliest days of programming. You're not gonna use them much. What you really want is > and <, which is for testing if numbers are greater than each other or less than each other.
In addition, you may remember from math class that ≥ and ≤ (greater-than-or-equal-to and less-than-or-equal-to) are useful operations as well. Because there's no symbols for those on most keyboards, however, C and Xcode use >= and <= instead.
Finally, you may already know this, but to check if two numbers are exactly equal to each other you can use == (because = is used for setting the contents of variables).
Hope that's helpful!

Related

Selection a bool through randomizer

I have a total of 6 booleans and the only thing separating them is a number. They're named checker0 though 5.
So checker0, checker1, checker2, checker3, checker4 and checker5.
All of these grants or denies access to certain parts of the app wether the bool is true or false.
I then have a randomiser using:
randomQuestionNumber = arc4random_uniform(5);
So say we get number 3, checker3 = true;
But my question now is would it be possible to set this one to true without having to go thru if statements.
My idea was to implement the way you print a int to say the NSLog using the %d.
NSLog(#"The number is: %d", randomQuestionNumber);
So something like:
checker%d, randomQuestionNumber = true.
Would something like that be possible? So i won't have to do like this:
if (randomQuestionNumber == 0) {
checker0 = true;
}
else if (randomQuestionNumber == 1)
{
checker1 = true;
}
Thanks you very much! :)
Every time you find yourself in a situation when you name three or more variables checkerN you know with a high degree of probability that you've missed a place in code where you should have declared an array. This becomes especially apparent when you need to choose one of N based on an integer index.
The best solution would be to change the declaration to checker[6], and using an index instead of changing the name. If this is not possible for some reason, you could still make an array of pointers, and use it to make modifications to your values, like this:
BOOL *ptrChecker[] = {&checker0, &checker1, &checker2, ...};
...
*ptrChecker[randomQuestionNumber] = true;

If statements not working correctly

I am developing an app where the user receives an overall score and are judged from that score and given a title. However, with the code I am using, the end result is always the same, no matter what score the subject gets. I dont know if this a math problem or a code problem, as it always comes up with the first option: You have no SWAG whatsoever...
if (totalScore<24) {
describe.text = #"You have no SWAG whatsoever...";
}
else if (25<totalScore<49) {
describe.text = #"You seem to be new to SWAG.";
}
else if (50<totalScore<74) {
describe.text = #"You have a bit of SWAG, not enough though.";
}
else if (75<totalScore<99) {
describe.text = #"You definately have SWAG!";
}
else if (totalScore == 100) {
describe.text = #"You are a GOD of SWAG.";
}
else if (25<totalScore<49) {
should be:
else if (25<totalScore && totalScore<49) {
The way you wrote it is parsed as if you'd written:
else if ((25<totalScore) < 49) {
25<totalScore will be either 1 or 0 depending on whether it's true or false. Either way, it's less than 49.
Also, all your comparisons should be <= rather than <. Otherwise, you're excluding all the boundary values.
building if in this way
if (25<totalScore<49) {...}
is risky.In reality you do something like
25<totalScore -> YES/NO (values will be casted from BOOL to int as 1/0)
and then you will do
0/1 < 49 which will be always true.
so in total your if is wrong.
Your first line of code looks right from what you have displayed so far? You need to output what total score is. You are maybe not setting it before running your code?
Failing that, are you sure its compiling properly? You need to use && in your subsequent if statements.
Also, you need to use <=, because at the moment, if the score is 24 it wont work.

else statement not triggering

I have been attempting to create an if else statement that will return a text string based on certain constraints. The first 3 constraints work, but when the event of the final constraint occurs, it triggers the second again. The random number generator occasionally used a 0 value, so I wanted to account for that. I am new to this, and apologize for indenting, etc.
I have been looking around here for a bit and couldn't find anything that seemed to cover this. If I missed it, a hint in the right direction would be appreciated as well.
double txtestimateCategory = [mynum computeVolume];
NSLog(#"The volume is %f", txtestimateCategory);
int v = ((txtestimateCategory * 1));
if ((v >= 8000))
{
NSLog(#"The box is large");
}
else if ((1 <= v < 1000))
{
NSLog(#"The box is small");
}
else if ((1000 <= v < 8000))
{
NSLog(#"The box is medium");
}
else
{
NSLog(#"The box is a lie");
}
Comparators are binary operators. You have to write:
else if (1 <= v && v < 1000)
etc.
(Otherwise you would be evaluating things like true < 1000, and true converts to 1 implicitly. Not what you meant!)

Is value "in" some other values, in objective-c

Coming from an extremely spoiled family upbringing (turbo pascal, python, ruby) I'm a bit puzzled when it comes to doing all the household chores myself.
Yesterday was one of these days where I just did not find myself a solution. I had to check whether a value matches one of some other values.
x = some_function_return_value();
if x in (1,4,17,29,35):
That's how I used to write it. Now with Objective-C I obviously can't do that. And I searched the old google, but found no answer, and the old manual, and nothing there, so how do you do this in Objective-C, without doing something cranky like the following?
if (x == 1 || x == 4 || x == 17 || x == ...) {
Edited: in this case it is an (int), I know for NSArray and NSString there are methods for this
If it's about integer values, you can use switch:
switch (x) {
case 1:
case 4:
case 17:
case 29:
case 35:
do_something();
break;
}
Do not forget that in C/C++/Objective-C, the cases fall through to the next by default. You need to add break; statements to prevent that.
For non-integer values, you have to do long if statements with a lot of repetition as C doesn't provide syntactic sugar or features that many scripting languages have to abbreviate this.
Another way would be for example to prepare an array and then do:
if ([myArray containsObject:[NSNumber numberWithInteger:x]])
or even better, use an NSSet for that. This will work for most objects, for example it will also work with strings.
There is a fast enumeration syntax in objective C that uses "in" to loop over collections, however given it requires converting your int values to NSNumbers, it's probably easier to use C here
BOOL success = NO;
int size = 5
NSInteger numbers[size] = {1,4,17,29,35};
for (int i = 0; i < size; i++) {
if (yourValue == numbers[i]) {
success = YES;
break;
}
}
if (success) {
/* do your stuff */
}
admittedly not as nice as python...
Here's my silly program of the day:
bool int_exists_in_array(const int n, const int a[], const size_t elementCount) {
return (0 != elementCount) &&
(n == a[0] || int_exists_in_array(n, a + 1, elementCount - 1U));
}
so this:
if x in (1,4,17,29,35):
becomes:
const int a[] = { 1, 4, 17, 29, 35 };
if (int_exists_in_array(x, a, sizeof(a)/sizeof(a[0]))) {
...
}
You can use NSSet in addition with NSValue.

Rounding with significant digits

In Xcode /Objective-C for the iPhone.
I have a float with the value 0.00004876544. How would I get it to display to two decimal places after the first significant number?
For example, 0.00004876544 would read 0.000049.
I didn't run this through a compiler to double-check it, but here's the basic jist of the algorithm (converted from the answer to this question):
-(float) round:(float)num toSignificantFigures:(int)n {
if(num == 0) {
return 0;
}
double d = ceil(log10(num < 0 ? -num: num));
int power = n - (int) d;
double magnitude = pow(10, power);
long shifted = round(num*magnitude);
return shifted/magnitude;
}
The important thing to remember is that Objective-C is a superset of C, so anything that is valid in C is also valid in Objective-C. This method uses C functions defined in math.h.