我有以下代码段:
int main()
{
int x, R, m;
double Y, D, P;
cout << "Enter investment: ";
cin >> x;
cout << "Enter rate per year: ";
cin >> R;
cout << "Enter months: ";
cin >> m;
/* Convert to years. */
Y = m / 12;
D = x * pow ((1 + (R/100)), Y);
P = D - x;
cout << "Investment after " << Y << " years is " << D << " bucks.\n";
cout << "Profit is " << Y << " year(s) is " << P << " bucks.\n";
我的cout结果未正确计算,并且由于某种原因我在结果中没有得到小数。
我怀疑它与数据类型有关。
答案 0 :(得分:2)
使至少一个操作数加倍以使其工作。
Y = m / 12.;
D = x * pow ((1 + (R/100.)), Y);
答案 1 :(得分:1)
D = x * pow ((1 + (R/100)), Y);
R/100
将产生一个整数,因为两个操作数都是整数。其中至少有一个必须double
才能正常工作。
D = x * pow ((1 + (R/100.0)), Y);