简体   繁体   中英

How do I go about getting decimals between 0 and 1?

I'm trying to get all of the decimals with 3 digits in them with a while loop until it gets to 1.00.

Like so:

0.00

0.01

0.02

0.03

and so on.

Any help is appreciated!

As @Mitch recommended in his comment, you should use decimal primitive type:

for (decimal i = 0m; i <= 1; i += 0.01m)
{
  Console.WriteLine(i);
}

If you want a numeric real literal to be treated as decimal , you need to use the suffix m or M . Without the suffix m , the number is treated as a double and generates a compiler error.

You should post what you've tried already, but this should get you there:

for (double i = 0; i <= 1; i += 0.01)
{
    i = Math.Round(i, 2);

    Console.WriteLine(i);
}

Good feedback in comments. This should get you there. Probably not the cleanest approach though.

for(int i=0; i<=100; i++) 
{
   Console.WriteLine(string.Format("{0:F2}",i/100.0));
}

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