-1

I want to show a 2 decimal point for the Average in the console.WritLine. Right now it showing a whole number.

string input = "";
int total=0 ;
int numbersEntered =0 ;
double average=0.00 ;

total += Convert.ToInt32(input);
numbersEntered++;
average = (total / numbersEntered);
Console.WriteLine("Total: {0}\t Numbers Entered: {1}\t Average: {2:#.##}\t", total, numbersEntered, average);
Console.ReadKey();
Dan Oberlam
  • 2,435
  • 9
  • 36
  • 54
Snow
  • 1
  • 5

3 Answers3

2

declare total and numbersEntered double as well. you are using int, then dividing integer with integer will return whole number not a double with 2 decimal point.

string input = "";
double total=0 ;
double numbersEntered =0 ;
double average=0.00 ;

total += Convert.ToInt32(input);
numbersEntered++;
average = (total / numbersEntered);
Console.WriteLine("Total: {0}\t Numbers Entered: {1}\t Average: {2:#.##}\t", total,    numbersEntered, average);
Console.ReadKey();
Aftab Ahmed
  • 1,727
  • 11
  • 15
1

I think this is C#? You probably want to add the tag to get better answers. If it is, try replacing your Console.WriteLine with this:

 Console.WriteLine("Total: {0}\t Numbers Entered: {1}\t Average: {2:F2}\t",
                   total, numbersEntered, average);

The documentation I found for this was here and here.

Sam Mussmann
  • 5,883
  • 2
  • 29
  • 43
0

Change

average = (total / numbersEntered);

to

average = ((double)total / numbersEntered);

The operator / between two integers does integer division. Only after the division is performed is the result (quotient) converted from int to double, but by then precision has already been lost.

I converted one of the operands (the left one) from int to double; the right operand will then automatcally be converted as well (the conversion from int to double is implicit). When the operands of the / operator are doubles, floating-point division is performed which is what you want.

Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181