无论我投入什么,我都会得到相同的答案
I keep getting the same answer, no matter what I put in
我们正在做一个计算机科学课上的作业,要求我们在用户输入的"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 值而变化
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 警告处理为错误这里有什么问题
- 什么时候调用组成单元对象的析构函数
- #定义c-预处理器常量..我做错了什么
- 努力将整数转换为链表。不知道我在这里做错了什么
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 什么时候在C++中返回常量引用是个好主意
- 当在同一名称空间中有两个具有相同签名的函数时,会发生什么
- C++避免重复声明的语法是什么
- 这个问题的答案应该是什么
- 无论我投入什么,我都会得到相同的答案
- 以下代码的输出是什么(答案因差异编译器而异)
- 什么stod("5.000e-M1")应该是答案?
- 程序运行而不会崩溃,但无论该人将什么作为变量,答案都是 0
- SPOJ:KURUK14的这两个答案有什么区别
- 这个C++测验答案背后的解释是什么
- 采访中问的这个问题可能是什么答案
- cout << a++ << a; 的正确答案是什么?
- C++考试修订版,不确定为什么正确答案是什么
- 如何计算对该函数的递归调用,以及正确答案是什么