我正在尝试制作一个简单的英尺转换器,但这种情况发生了:
using System;
using System.Windows;
using System.Windows.Controls;
namespace CoolConversion
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
decimal feet;
decimal meter;
public MainWindow()
{
InitializeComponent();
}
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
feet = Convert.ToDecimal(Feet.Text);
meter = feet / 3.281;
}
}
}
这是我目前的代码.起初,脚和&米是int,但我不能将int除以3.281.我将它们更改为小数,现在我有这个错误:
Error CS0019 Operator ‘/’ cannot be applied to operands of type
‘decimal’ and ‘double’
如果我不能用小数除以小数,如果我不能在小数上使用/符号,我应该如何除以小数?
解决方法:
这里的问题是编译器认为你的常量3.281是double类型.如果您打算使用十进制等类型,则必须附加m后缀.与浮点类型类似,您必须附加f后缀.每个MSDN:
By default, a real numeric literal on the right side of the assignment operator is treated as
double
.
Therefore, to initialize a
float
variable, use the suffixf
orF
, as in the following example:float x = 3.5F;
However, if you want an integer number to be treated as
double
, use the suffixd
orD
, for example:double x = 3D;
If you want a numeric real literal to be treated as
decimal
, use the suffixm
orM
, for example:decimal myMoney = 300.5m;
我的建议
您应该确定在使用之前实际需要使用哪种类型.在将脚转换为米的情况下,我会使用双倍或浮动; double通常就是这种情况,因为它更精确.
private double feet = 0.0d;
private double meters = 0.0d;
private void TextBox_TextChanged(object sender, TextChangedEventArgs e) {
feet = Convert.ToDouble(Feet.Text);
meters = feet / 3.281d;
}
十进制类型通常用于保存货币值,其中double和float用于此类计算.此外,它不是一个要求,但如果你曾经使用过多种类似的类型,例如float,double,decimal;使用每个后缀来清楚地传递您打算使用的类型总是一个好主意.
最后的说明
您可以像其他人指出的那样强制转换为十进制,但是当您可以使用3.281m指定十进制时,这是一个不必要的强制转换.在性能很重要的环境中,应尽可能避免不必要的转换.
另外,在尝试转换之前,您应该确保您尝试转换的文本是有效值.我更喜欢使用TryParse
(如果我没记错的话,所有数字类型应该有一个TryParse方法).这背后的原因是,如果我按照你的方法目前的工作方式在你的文本框中键入123a,那么它会立即爆炸.解决这个问题非常简单:
private void TextBox_TextChanged(object sender, TextChangedEventArgs e) {
if (double.TryParse(Feet.Text, out feet))
meters = feet / 3.281d;
else
MessageBox.Show($"You've entered an invalid value: {Feet.Text}.");
}