我正在通过制作一个简单的小费计算器来学习Objective-C和iOS开发。但是,我遇到的问题是当我尝试计算小费时。这是简单的数学(小费百分比/总账单)* 100。这正是我正在做的事情,但我真的很困惑为什么我的输出是错误的。
这是我的ViewController.m文件中给我带来问题的方法
- (IBAction)doCalculate:(id)sender {
NSInteger totalBillAmount = self.inputTotalBill.text.intValue;
NSLog(@"input total bill: %i", totalBillAmount);
NSInteger tipPercent = self.inputTip.text.intValue;
NSLog(@"input tip percent: %i", tipPercent);
NSInteger tipAmount = (tipPercent / totalBillAmount) * 100;
NSLog(@"tip amount: %i", tipAmount);
NSInteger billAmount = totalBillAmount + tipAmount;
NSLog(@"total bill: %i", billAmount);
// Set labels accordingly
self.labelTipAmount.text = [NSString stringWithFormat:@"%i", tipAmount];
self.labelBillAmount.text = [NSString stringWithFormat:@"%i", billAmount];
}
这是我的输出:
2016-02-28 01:39:36.283 conversion[1533:58347] input total bill: 100
2016-02-28 01:39:36.285 conversion[1533:58347] input tip percent: 15
2016-02-28 01:39:36.285 conversion[1533:58347] tip amount: 0
2016-02-28 01:39:36.285 conversion[1533:58347] total bill: 100
我真的很困惑,所以任何帮助都值得赞赏,谢谢!
计算机数字的行为与您在学校学到的数字不同。整数只使用整数算术,然后使用整数除法(在网上看)。
4/100(作为整数除法)给出 0(还记得欧几里得除法吗?如果你想进行更自然的计算,请使用浮点数或双精度(但它们稍后会让你更加惊讶!
当你划分两个 NSInteger 时,结果是一个 NSInteger。如果该分数为 <1 和>0,则输出为 0。如果您希望NSInteger简单,则使用NSInteger可能不是最佳选择。
NSInteger tipAmount = (tipPercent * totalBillAmount) / 100;
NSLog(@"tip amount: %i", tipAmount); // tip amount: 0
如果你使用浮子,它会干净得多:
float tipAmount = (tipPercent * totalBillAmount) / 100;
NSLog(@"tip amount: $%.02f", tipAmount); // tip amount: $15.00
但是,使用浮动作为货币可能非常糟糕。因此,使用NSInteger来跟踪最小的货币单位将是一个更明智的决定。对于美元,这是 0.001 美元,或十分之一美分。
这意味着,当有人输入账单总额时,假设 $100.00,您将该值记录为 100000。
然后,要计算 15%,您需要将账单乘以 15,然后除以 100。
NSInteger tipAmount = (tipPercent * totalBillAmount) / 100;
NSLog(@"tip amount: %i", tipAmount); // tip amount: 15000
为了再次向用户显示,我将使用如下所示的方法将第十美分单位转换为美元的格式化字符串:
- (NSString *)tenthCentToDollarString:(NSInteger)tenthCents {
if (tenthCents >= 0) {
NSInteger roundedCents = (tenthCents + 5) / 10;
if (roundedCents < 10) {
return [NSString stringWithFormat:@"$0.0%zd", roundedCents];
}
if (roundedCents < 100) {
return [NSString stringWithFormat:@"$0.%zd", roundedCents];
}
NSInteger cents = roundedCents % 100;
NSInteger dollars = roundedCents / 100;
if (cents < 10) {
return [NSString stringWithFormat:@"$%zd.0%zd", dollars, cents];
}
return [NSString stringWithFormat:@"$%zd.%zd", dollars, cents];
}
// Dollar amount is negative
NSInteger positiveTenthCents = ABS(tenthCents);
NSString *dollarString = [self tenthCentToDollarString:positiveTenthCents];
return [NSString stringWithFormat:@"-%@", dollarString];
}
几个问题:你应该做tipAmount = (tipPercent / 100) * totalBillAmount
并投射到双精度,因为 NSInts 不能做分数。