Cannot assign value of quotient when declaring a double


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. It doesn't seem to work...


double convert = 5 / 1024;



This keeps assigning the value 0 to the variable 'convert' instead of 0.0048828125.



I am using it in a serial read to convert the 10-bit integer back to a voltage...


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. I just can't assign the conversion double with the expression "5 / 1024".





Possible duplicate of Why does integer division in C# return an integer and not a float?
– Camilo Terevinto
Jun 29 at 21:53




2 Answers
2



That (5 / 1024) is integer division. In integer division: the answer is zero. To tell it to use floating point: add a decimal point:


5 / 1024


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).



Example:
double convert = 5d / 1024d;


double convert = 5d / 1024d;






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

Opening a url is failing in Swift

Export result set on Dbeaver to CSV