我对此非常绝望。它应该很容易但不知何故我做错了。
我有这个代码来显示一个众所周知的物理方程的结果,但是我似乎没有得到答案的小数。如果答案是2.5我得到2.00如果它是0.2我得到0.00。有人能想出为什么吗?
在.h文件中:
@interface MyController : UIViewController {
float result;
}
@property (strong, nonatomic) IBOutlet UILabel *VariableResult;
在.m文件中:
if ([VariableSelected.text isEqual: @"Position"]) {
result = [VelocityVariable.text intValue] * [AccelerationVariable.text intValue] * [TimeVariable.text intValue];
VariableResult.text = [NSString stringWithFormat:@"%2f", result];
}
答案 0 :(得分:1)
整数乘以整数,仍然是整数。您应该获得floatValue
而不是intValue
,即
result = [VelocityVariable.text floatValue]
* [AccelerationVariable.text floatValue]
* [TimeVariable.text floatValue];
您也可以考虑使用NSNumberFormatter
NSNumberFormatter* nf = [[NSNumberFormatter alloc] init];
nf.positiveFormat = @"0.##";
VariableResult.text = [nf stringFromNumber:[NSNumber numberWithFloat:result]];
答案 1 :(得分:1)
您将int
值乘以获得此结果的原因,将intValue
替换为floatValue
,如下所示
if ([VariableSelected.text isEqual: @"Position"])
{
result = [VelocityVariable.text floatValue] * [AccelerationVariable.text floatValue] * [TimeVariable.text floatValue];
VariableResult.text = [NSString stringWithFormat:@"%2f", result];
}