我总是被告知永远不要代表钱double或float类型,这次我向你提出问题:为什么?
我确信有一个很好的理由,我根本不知道它是什么.
我正在开发一款iPhone应用程序并且希望代表金额($)金额.我不能使用float因为它们会引入一定量的舍入错误.我可以用什么?
我正在考虑定义我自己的Money类,并在内部存储美元和便士作为NSInteger.
@interface Money : NSObject {
//$10.25 is stored as dollas=10 and pennies=25
NSInteger dollars;
NSInteger pennies;
}
Run Code Online (Sandbox Code Playgroud)
另一种可能的表示(更容易添加和乘法)将使用单个NSInteger作为便士.
@interface Money : NSObject {
//$10.25 is stored as pennies=1025
NSInteger pennies;
}
Run Code Online (Sandbox Code Playgroud)
你的想法是什么?我可以使用"BigDecimal"类型吗?
我已经创建了一个ATM程序,它将钱存入一个人的账户.当该人取出提款时,它会从账户中扣除50%的附加费.我遇到的问题是在这个程序中使用整数和浮点数.我将整数帐户转换为浮点数,但是当我尝试打印语句时收到错误消息.有人能告诉我我做错了什么吗?
#include <stdio.h>
int main (void) {
int account = 2000;
int withdrawal;
float charge = 0.50;
printf ("How much money would you like to take out? ");
scanf ("%i", &withdrawal);
while (withdrawal % 5 != 0) {
printf ("Withdrawal must be divisible by 5. ");
scanf("%i", &withdrawal);
}
account = ((float) account - charge) - withdrawal;
printf("Remaining account: %.2f\n", account);
return 0;
}
Run Code Online (Sandbox Code Playgroud) 我不明白为什么不roundf()从功能math.h全面的donation变量,而这轮livestockPM没有问题.我需要使用舍入值进行其他计算,但我printf用来检查值是否正确,并且它只返回错误的值(不会舍入变量donation).此外,变量final只返回值,好像四舍五入为.00,无论什么变量farmer1,2,3保持.
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main(){
int farmer1 = 9940;
int farmer2 = 4241;
int farmer3 = 7779;
float livestockPM = (float)farmer1 / (float)farmer2;
printf("livestock: %f\n",livestockPM);
livestockPM = roundf(livestockPM * 100) / 100;
printf("livestock rounded: %f\n",livestockPM);
float donation = (float)livestockPM * (float)farmer3;
printf("donation: %f\n", donation);
donation = roundf(donation * 100.00) / 100.00;
printf("donation rounded: %f\n", donation);
float final = donation * (float)farmer2;
printf("final: %f\n", …Run Code Online (Sandbox Code Playgroud) 我想知道在C中读取和存储货币值的最佳方法是什么,例如11.22.
我试过scan("%f", &num),但我在浮动结束时得到随机值.
有没有办法只读到小数点后第二位?
如果我添加这些数字,它们就不准确; 由于某种原因它倒圆了.添加11.22 + 22.33优于11.220000 + 22.330000,因为我在最后得到随机值; 我不知道为什么!
如果超出小数点后第二位并且用户输入了一个字符,是否有办法将错误返回给用户.
我在考虑将(数组)字符串转换为浮点数.