I have difficulties calculating percentage of a double value. I wrote the code below but it always show "0". What can be the problem?
double percent = 80; //Percent
double toCalc = 1/1000000; //1 uAmper
MessageBox.Show((toCalc * (pe开发者_StackOverflow社区rcent / 100F)).ToString());
Thanks.
1/1000000
needs to be performed as a floating point division. I'd write it like this:
1.0/1000000.0
The way you wrote it, the division will be performed as an integer division, and then promoted to a floating point value. The integer division results in 0 which explains what you are seeing.
This line is wrong:
double toCalc = 1/1000000; //1 uAmper
since you are assigning 0 to toCalc
. That's why it always displays zero.
You should change it to
double toCalc = 1/1000000d;
That's because it first calculates 1/1000000 that, for integral types, evaluates to 0. Then, it is cast to double, but it's still 0.
精彩评论