Mat*_*cer 0 iphone math objective-c
我有一个不起作用的计算,我无法弄明白为什么!
int numHoursInWeek;
int numDays;
int averageSalary;
int total_seconds_in_year = ((numHoursInWeek * 60 * 60) * numDays);
NSLog(@"average sal in pence=%i", (averageSalary * 100));
NSLog(@"num seconds in year=%i", total_seconds_in_year);
NSLog(@"cost per second=%i", ((averageSalary * 100) / total_seconds_in_year));
int cost_per_person_per_second = ((averageSalary*100) / total_seconds_in_year);
costPerSecond = (cost_per_person_per_second * numPeople);
lblCostPerPerson.text = [NSString stringWithFormat:@"%.2f",cost_per_person_per_second];
Run Code Online (Sandbox Code Playgroud)
以上内容在NSLog中返回以下内容
average sal in pence=3400000
num seconds in year=31968000
cost per second=-1.991753
Run Code Online (Sandbox Code Playgroud)
我知道其他一切设置正确(例如,numDays,averageSalary).当我手动进行计算时,我得到0.1063.那应该显示在我的标签上?(每人每秒的费用).
有任何想法吗?我应该使用浮点数而不是整数的整数?
进行整数除法时,数字会被截断,因此:
6 / 4
>>> 1
Run Code Online (Sandbox Code Playgroud)
将您的数据类型更改为float或double,并将所有数字写为"100.0" - 否则将被视为int.