[英]simple c++ program about calculation of percentage of user input
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int amount;
int discount;
cout<<"please enter amount : ";
cin>>amount;
discount = amount*(10/100);
cout<<"the discount amount is"<<discount<<endl;
system("PAUSE");
}
i am writing simple c++ program in which i wanted to get answer of input digits entered by user the simple mathematical equation is calculating in int amount variable but its not giving a required answer its giving a 0 but the code is correct i guess.我正在编写简单的 C++ 程序,我想在其中获得用户输入的输入数字的答案,简单的数学方程正在计算 int 量变量,但它没有给出所需的答案,它给出了 0,但我猜代码是正确的。
10/100
is integer division, which results in 0
. 10/100
是整数除法,结果为0
。 Hence you multiply the amount by zero, netting zero again.因此,您将金额乘以零,再次净额为零。
Edit:编辑:
In case you come from a dynamic language like JavaScript or Python, they often use implicit double variables for everything, hence this would give you the expected value.如果你来自像 JavaScript 或 Python 这样的动态语言,它们通常对所有东西都使用隐式双变量,因此这会给你预期的值。 C++ has a much stronger type system, so integral division will always yield another integer. C++ 有一个更强大的类型系统,所以整数除法总是会产生另一个整数。 If you wanted a division of floating point values you need to use floating point literals (or cast, but in this case it's not necessary):如果您想要对浮点值进行除法,则需要使用浮点文字(或强制转换,但在这种情况下没有必要):
discount = amount * 10.0 / 100.0;
Or, if float
is enough precision for you:或者,如果float
对您来说足够精确:
discount = amount * 10.0f / 100.0f;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.