简体   繁体   中英

C# Console application % math always return 0

Hello guys i have a small problem at my console application i have a text file got 19862 line

String[] lines= File.ReadAllLines("C:\\Users\\ThElitEyeS\\Desktop\\PHP\\name\\names.txt");
int c = lines.Length;
int i = 1;
foreach (String line in lines) {
    long f = ((i++ / c) * 100);
    Console.WriteLine(f + "%");
}

the value always return 0% except the last one its return 100% and that is my problem i hope to find question fast :)

You are making a integer devision and that will be rounded.

Example:

i = 1 and c= 100
result is 0.01  -> rounded to 0
0 * 100 = 0

Instead try

long f = ((i++ / (double) c) * 100);

to force a floating point devision.

您已经有了一个有效的答案,但是当整数除法(不舍入但截断)就足够了时,在这里我不会使用double

long f = i++ * 100 / c;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM