Basically, the program has 5 textfields for numbers. I wan开发者_如何学JAVAt a math function that totals all 5 textboxes, then multiplies by 1.39, then again by 1.12, but I can't get the textfields to add properly. It works so far if you only put a number in one of the textfields, but it gets a little confused when it comes to adding more than one textfield. Here's my code:
- (IBAction)calculate {
float b = ([BCB.text floatValue]);
float d = b+([MCD.text floatValue]);
float f = b+d+([SF.text floatValue]);
float w = b+d+f+([SW.text floatValue]);
float a = b+d+f+w+([AP.text floatValue]);
float p = 1.39f;
float h = 1.12f;
float t = a*p*h;
Total.text = [ [NSString alloc] initWithFormat:@"%.2f", t];
}
Bear in mind I'm 100% beginner when it comes to Xcode, and I've kind of Frankensteined this code together from various tutorials, and this might be completely wrong.
In the line:
float f = b+d+([SF.text floatValue]);
d
already equals b+([MCD.text floatValue])
, so f
is assigned the value of 2*b + ([MCD.text floatValue])
, and more error builds up in the next two lines. Just assign each floatValue to a variable by itself (i.e., float f = [SF.text floatValue];
and so on) and then add them all together at the end.
You should add the value of each text field only once, e.g.:
- (IBAction)calculate {
float b = [BCB.text floatValue];
float d = [MCD.text floatValue];
float f = [SF.text floatValue];
float w = [SW.text floatValue];
float a = [AP.text floatValue];
float p = 1.39f;
float h = 1.12f;
float t = (b+d+f+w+a)*p*h;
Total.text = [ [NSString alloc] initWithFormat:@"%.2f", t];
}
精彩评论