Re: [2.0] how decimal work?
In C-based languages the result of dividing an integer by an integer is always an integer. If you want the result to be a decimal then at least one of the numbers must be a decimal. Change this:
C# Code:
ave = (nmb1 + nmb2 + nmb3) / 3;
to this:
C# Code:
ave = (nmb1 + nmb2 + nmb3) / 3M;
and you'll get the result you want. Note that the "M" suffix is short for "money" and forces the preceding number to type decimal. Alternatively you could do this:
C# Code:
ave = Convert.ToDecimal(nmb1 + nmb2 + nmb3) / 3;
or this:
C# Code:
ave = (nmb1 + nmb2 + nmb3) / (decimal)3;
Re: [2.0] how decimal work?
or just:
Code:
ave = (nmb1 + nmb2 + nmb3) / 3.0;
Note that it would be more elegant to use an array, as then you can handle an indefinite number of values.
Re: [2.0] how decimal work?
Quote:
Originally Posted by penagate
or just:
Code:
ave = (nmb1 + nmb2 + nmb3) / 3.0;
Note that it would be more elegant to use an array, as then you can handle an indefinite number of values.
That will actually not work because 3.0 is type double so that expression will actually return a double rather than a decimal. As such you'd have to convert the result before you could assign it to a decimal variable. If you were assigning to a double variable it would be fine and proper.
I guess the problem here is also that what's being calculated is an average and in many cases the number on the bottom will be an integer variable. In that case it would be most correct to convert the number on the top to the type you want the result to be.