Farhad-Taran
Farhad-Taran

Reputation: 6512

why cant i see the decimal point numbers in c#?

int total = 201;

double Average = total / 7;

result should be 28.71428571428571.

I've tried float, decimal and double for Average but the result ends up as 28.

Upvotes: 0

Views: 322

Answers (5)

Kyle Trauberman
Kyle Trauberman

Reputation: 25684

Because an int divided by an int is always an int.

try this:

double average = total / 7.0;

Upvotes: 1

Mike Christensen
Mike Christensen

Reputation: 91608

You can use the D suffix to implicitly state the operand is a double, for example:

201 / 7
28

201 / 7D
28.714285714285715

Or:

double Average = total / 7D;

Upvotes: 2

Stilgar
Stilgar

Reputation: 23551

the total is int and 7 is int. The resul of integer division is int. It gets cast AFTER that to double but this does not matter because it is already truncated. Try:

double average = total / 7.0;

7.0 is a double literal and the result of int and double division is double.

Upvotes: 1

froadie
froadie

Reputation: 83053

It's doing integer arithmetic, because total is an int, and 7 is an int. If you change either of them to decimal you'll get the result you're looking for.

e.g.

int total = 201;

double Average = total / 7.0;

Upvotes: 2

Matt
Matt

Reputation: 7160

You are doing integer division!

201/7 is entirely integral, and so the result doesn't even touch floats, instead you need to cast to a double first:

double Average = (double)total / 7.0;

Upvotes: 11

Related Questions