Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

c# - Why I cannot the get percentage by using Int

Please forgive my programming knowledge. I know this is a simple thing, but I do not understand why result is always 0. Why decimal will be fine?

int a = 100;
int b = 200;
decimal c = (a / b) * 100;

Many thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Integer division always truncates the remainder. This is done at the time that the number is divided, not when it's assigned to the variable (as I'm guessing you assumed).

decimal c = ((decimal)a / b) * 100;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...