سؤال

Why is the output "0 and 0"? How do I fix it?

 Int64 small=  (long)0.25 * (long)Int64.MaxValue;
 Int64 large = (long)0.75 * (long)Int64.MaxValue;
 System.Console.WriteLine(small + " and " + large);
 System.Console.ReadLine(); 
 //output 
 //0 and 0 
هل كانت مفيدة؟

المحلول

Statement (long)0.75 will return 0 (converting double to long will take greatest integer value, that is lower that converting double). So you have 0 * 9223372036854775807 which is hopefully 0. By the way long is alias for Int64, which means they are the same underlying types, so by (long)Int64.MaxValue you casting long to long

to fix it simply use double * long multiplication

long small=  (long)(0.25 * long.MaxValue);
long large = (long)(0.75 * long.MaxValue);

Console.WriteLine ("{0:N}", small); //print 2,305,843,009,213,693,952.00
Console.WriteLine ("{0:N}", large); //print 6,917,529,027,641,081,856.00

don't bother with "{0:N}" literal, it's simply a format to give the output some visual beauty. By default double is printed in scientific notation, which is not so demonstrable (for example 2.30584300921369E+18 for first operation)

نصائح أخرى

The reason why is that in both cases you are converting a value which is less than 1 to a long. This will truncate the value to 0 hence the multiplication also results in 0

Console.WriteLine((long)0.25);  // 0
Console.WriteLine((long)0.75);  // 0

Because 0.25 and 0.75 casted as long are 0.

In order to remedy that, you will need to use floats or doubles. However, I'm not 100% certain the precision is enough to lead to exact results:

Int64 small=  (Int64)(0.25 * (double)Int64.MaxValue);
Int64 large = (Int64)(0.75 * (double)Int64.MaxValue);

You want to convert after not before the multiplication. Try

 Int64 small=  (long) (0.25 * (double) Int64.MaxValue);

Before you were converting .25 to long which is 0.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top