简体   繁体   English

声明双精度时无法分配商的值

[英]Cannot assign value of quotient when declaring a double

I'm trying to declare a double in C# that has the value of a quotient. 我试图在C#中声明一个具有商值的double。 It doesn't seem to work... 它似乎不起作用...

double convert = 5 / 1024;

This keeps assigning the value 0 to the variable 'convert' instead of 0.0048828125. 这将继续为变量“ convert”分配值0,而不是0.0048828125。

I am using it in a serial read to convert the 10-bit integer back to a voltage... 我在串行读取中使用它来将10位整数转换回电压...

static void Main(string[] args)
{
    double rawValue;
    double convert = 5 / 1024; // Assigns value of 0
    double convValue;
    string read;

    SerialPort sp = new SerialPort("COM3"); // Creates COM port 
    sp.BaudRate = 9600;
    sp.Open();

    for (;;)            
    {
        read = sp.ReadLine();
        rawValue = Convert.ToDouble(read);
        convValue = rawValue * convert;
        Console.WriteLine(Math.Round(convValue, 2));
    }
}

The serial read works fine; 串行读取工作正常; I can read and write to the console the 0-1023 number and then converter it manually. 我可以在控制台上读写0-1023号,然后手动对其进行转换。 I just can't assign the conversion double with the expression "5 / 1024". 我只是无法将表达式“ 5/1024”分配给转换倍数。

That ( 5 / 1024 ) is integer division. 那( 5 / 1024 )是整数除法。 In integer division: the answer is zero. 用整数除法:答案为零。 To tell it to use floating point: add a decimal point: 告诉它使用浮点:添加一个小数点:

double convert = 5.0 / 1024;

Note it can also probably be declared const . 注意它也可能被声明为const

Try inserting a "D" after the number, this way, the compiler can identify, with clarity, the desired type (in this case, the literal "D" represents the double type, just like "M" represents decimals). 尝试在数字后面插入“ D”,这样,编译器可以清楚地标识所需的类型(在这种情况下,文字“ D”代表双精度类型,就像“ M”代表小数)。

Example: 例:
double convert = 5d / 1024d;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM