Sam*_*m G 1 null objective-c nsstring ios
我可能遗漏了一些明显的东西(仍在学习Objective-C!)但由于某种原因,我的一个NSString变量在我的if语句中有一个空值,我不知道为什么?
我甚至输出到NSLog,我仍然不明白为什么它的行为是这样的.
基本上,用户在文本字段(itemWeight)中输入金额,此if语句验证输入并根据结果显示警报.问题似乎只是在输入0.751时,如果输入任何其他数量(0.750,0.749,0.752,0.753等),它按预期工作.
相关代码示例如下......
.h文件:
@property (strong, nonatomic) IBOutlet UITextField *itemWeight;
Run Code Online (Sandbox Code Playgroud)
.m文件:
NSString *rawWeightText = itemWeight.text;
float convertedWeightText = rawWeightText.floatValue;
NSString *weightMessage;
if (convertedWeightText <= 0.750)
{
weightMessage = @"under 0.750";
}
else if (convertedWeightText >= 0.751)
{
weightMessage = @"0.751 or over";
}
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: @"Error"
message: weightMessage
delegate: nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
Run Code Online (Sandbox Code Playgroud)
谢天谢地,任何我出错的想法/我忘记做的事情都会非常感谢!
查看if-else if条件的条件不具有from的范围 0.750 to 0.751.
浮点值必须小心比较.你应该考虑0.751可能性0.75099999...
以下循环,结果是99.999046,而不是100.继续添加更多精度差.
float a= 0.1f;
float result = 0.f;
for(int i = 0; i<1000; i++)
{
result += 0.1f;
}
printf("result:%f", result); //99.999046
Run Code Online (Sandbox Code Playgroud)
因此,一般情况下,不建议对这些表达式进行比较.
if (result == expectedResult)
Run Code Online (Sandbox Code Playgroud)
建议编写以下方法进行比较.
bool AlmostEqualRelative(float A, float B, float maxRelativeError)
{
if (A == B)
return true;
float relativeError = fabs((A - B) / B);
if (relativeError <= maxRelativeError)
return true;
return false;
}
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请阅读此处
http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm
另外,你必须阅读这个维基:
http://en.wikipedia.org/wiki/Floating_point
http://en.wikipedia.org/wiki/Denormal_number
| 归档时间: |
|
| 查看次数: |
498 次 |
| 最近记录: |