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

时间:2018-01-31 16:03:56

标签: c++

我们正在计算机科学课上完成一项任务,要求我们在用户输入的“n”年后找到投资的未来价值。它是用C ++编写的。这是我现在拥有的代码:

InMemory

无论我输入什么“n”,我都会以1000的答案结束。有人能告诉我代码有什么问题吗?

2 个答案:

答案 0 :(得分:0)

i的数据类型为int,因此您的浮点值i将被舍入为0,并且您将最终得到相同的输出与您的n值无关。将i和FV变量的数据类型从int更改为float,然后根据键入的n值更改输出

答案 1 :(得分:0)

#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!对于带小数点的数字,请使用float而不是int!

相关问题