[英]Divide a whole number by a decimal number
I am trying to divide a whole number by a decimal/float/double. 我正在尝试将整数除以十进制/浮点数/双精度数。 I am able to divide whole numbers just find using:
int Num1 = 300 / 2;
我能够将整数除以使用:
int Num1 = 300 / 2;
, but when I try to make that "2" a decimal it won't work. ,但是当我尝试将“ 2”设为小数时,它将无法正常工作。 I have seen people mention doing this
int Num1 = 300 / ((float)1.25);
我见过有人提到这样做
int Num1 = 300 / ((float)1.25);
. 。 That honestly doesn't make any sense to me... I have also tried
int Num1 = Decimal.Divide(300, 1.25);
老实说,这对我没有任何意义...我也尝试过
int Num1 = Decimal.Divide(300, 1.25);
without any luck.. 没有运气..
The problem is that you're trying to save the the result to an int
. 问题是您正在尝试将结果保存到
int
。 Try this: 尝试这个:
float result = 300 / (float)2;
float result = 300 / (float)1.25;
Or for more brevity (the f
is a signal to the compiler that this is a float
constant): 或者更简洁(
f
是向编译器发出的信号,它是一个float
常量):
float result = 300 / 2f;
float result = 300 / 1.25f;
Note that float
is very different from a decimal
, and both have their advantages. 请注意,
float
与decimal
有很大不同,两者都有其优点。 To use a decimal: 要使用小数:
decimal result = decimal.Divide(300, 1.25);
Or this (the m
is a signal to the compiler that this is a decimal
constant): 或这(
m
是向编译器发出的信号,它是一个decimal
常数):
decimal result = decimal.Divide(300m, 1.25m);
Simply put: 简单的说:
You are trying to store the result in an integer. 您正在尝试将结果存储为整数。 Instead use a double as the type of the variable to store the result:
而是使用double作为变量的类型来存储结果:
double Num1 = 300 / 2;
double Num1 = 300 / 1.25;
An int
can only store whole numbers. 一个
int
只能存储整数。 When you divide a whole number by a decimal, the output will be a decimal (even if you use 4.00
because of the way floating points are stored). 用整数除以小数时,输出将是小数(即使由于浮点存储方式而使用
4.00
)。
This won't compile 这不会编译
int Num1 = 300 / ((float)1.25);
Even though you're casting an explicit float (otherwise 1.25 would be a double
), you're trying to store it in a variable of type int
. 即使您正在强制转换显式float(否则1.25将是
double
),您仍试图将其存储在int
类型的变量中。 The compiler will not do this automatically because an implicit conversion doesn't exist for it to cast a float
as an int
for you. 编译器不会自动执行此操作,因为不存在隐式转换 ,编译器无法将
float
为int
。 Therefore, you need to either tell the compiler that you don't mind losing the precision and cast it as an int 因此,您需要告诉编译器您不介意丢失精度并将其强制转换为int
int Num1 = (int)(300 / ((float)1.25));
Or you can change the type of Num1
to be a float. 或者,您可以将
Num1
的类型更改为浮点数。
float Num1 = 300 / ((float)1.25);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.