无论我投入什么,我都会得到相同的答案

I keep getting the same answer, no matter what I put in

本文关键字:答案 什么      更新时间:2023-10-16

我们正在做一个计算机科学课上的作业,要求我们在用户输入的"n"年数后找到投资的未来价值。它是用C++写的。这是我现在拥有的代码:

#include <iostream>
using namespace std;
int main() {
int P=1000;
int i=0.0275;
int FV;
int n;
cout << "enter number of years:"<< endl;
cin >> n;
cout << "the future value is:"<< endl;
FV = P*(1+(i*n));
cout << FV << endl;
return 0;
}

无论我输入什么"n",我都会得到 1000 的答案。有人可以告诉我代码出了什么问题吗?

#include <iostream>
using namespace std;
int main() {
int P=1000;
float i=0.0275; //float instead of int
float FV; //FV should also be float as it will be storing decimal values
int n;
cout << "enter number of years:"<< endl;
cin >> n;
cout << "the future value is:"<< endl;
FV = P*(1+(i*n));
cout << FV << endl;
return 0;
}

您所做的错误是您分配给变量的类型! 由于 int 只处理整数值,我变成 0,你的结果变成 1000! 使用浮点数而不是整数来表示带小数点的数字!

i 的数据类型是 int,因此您的浮点值 i 将四舍五入为 0,您最终将获得相同的输出,无论您的 n 值是多少。将 i 和 FV 的数据类型从 int 更改为浮点数,然后输出会根据您键入的 n 值而变化