Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c# - simple calculation not working for some reason

Alright, I'm trying to calculate the percentage of two values. This should be really simple but for some weird reason it's not working. I'm too tired/dumb to figure it out. Here's my code, it keeps returning 0, i checked the values while debugging and with FilesCompleted being 295 and TotalFilesCount being 25002 the returnvalue var is just 0, it should be 1 already.

private int CalculatePercentComplete(int FilesCompleted, int TotalFilesCount)
        {
            int returnvalue = (FilesCompleted / TotalFilesCount) * 100;

            if (returnvalue > 100 || returnvalue < 1) return 1;
            else return returnvalue;
        }
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

i checked the values while debugging and with FilesCompleted being 295 and TotalFilesCount being 25002 the returnvalue var is just 0, it should be 1 already.

No, because all the arithmetic is being done with integers. So first this expression is evaluated:

(FilesCompleted / TotalFilesCount)

That's 295 / 25002. The result of that integer arithmetic is 0... and when you then multiply it by 100, you've still got 0. The simplest fix is just to do the multiplication first:

int returnvalue = (FilesCompleted * 100) / TotalFilesCount;

Note that that will overflow if FilesCompleted is greater than int.MaxValue / 100. You could fix that by either doing everything in floating point arithmetic:

int returnvalue = (int)((FilesCompleted * 100.0) / TotalFilesCount);

... or by using long integer arithmetic:

int returnvalue = (int)((FilesCompleted * 100L) / TotalFilesCount);

Neither of these are necessary if you don't expect to have an insane number of files, of course. (You're fine up to 42 million files...)

As a side note, your parameter names violate .NET naming conventions. They should be camelCased - totalFilesCount and filesCompleted.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...