To make a button square the value of the mainLabel, I am using
- (IBAction)squarePressed:(id)sender
{
NSString *mainLabelString = mainLabel.text;
int mainLabelValue = [mainLabelString intValue];
NSString *calculatedValue = [NSString stringWithFormat: @"%d", mainLabelValue*mainLabelValue];
mainLabel.text = calculatedValue;
}
No erros are shown, and it works well with small numbers,
for example, the result of squaring 720 is correct, 518400, but if I try to square that number, instead of 268738560000, I get -1844379648.
Why is this happening?
That’s a numeric overflow, use a long long if you want to use the highest number of bits avoiding the overflow.Also a long double would be good, but not so precise.
Of course if you use high numbers also this way it may occur an overflow, but it occurs for higher values, depending on the bits difference from int to long long int.