0

I want to print decimal numbers from 0.1 to 0.100 In a loop, how can you print with increment?

for(decimal i=0.1;i<=0.100;i++)
{
   console.writeline(i);
}

My decimal value getting change from 0.10 to 1.0.

want to print 0.1 , 0.2, 0.3... 0.10,0.11, 0.12...0.100

cr7oo
  • 155
  • 8
  • 5
    FYI, in math, `0.1` and `0.100` are the same number, so `0.1 == 0.100` is true (well, [floating point math is (famously) broken](https://stackoverflow.com/questions/588004/is-floating-point-math-broken)) – MindSwipe Oct 19 '22 at 06:38
  • 2
    I think the easiest way would be to iterate over `int`s and simply print a 'dummy' decimal number: [Example fiddle](https://dotnetfiddle.net/9uc9ft) – Astrid E. Oct 19 '22 at 06:44
  • 0.1 and 0.100 are the same number, so you actually don't want to output values from one to the other. – jmcilhinney Oct 19 '22 at 06:51
  • 2
    Given the results you desire, my impression is that you don't actually want numbers in the mathematical sense, but rather a special sequence for some other reason. – ProgrammingLlama Oct 19 '22 at 06:54

3 Answers3

3

Well the root problem is that 0.1 and 0.100 are the same number. Also that i++ is syntactic sugar, it is equal to i = i + 1. It seems like you don't want the numbers in the mathematical sense, but in the "version" sense (like version 1.1 is older than 1.10), and in that sense each number (before or after the dot) is treated as a natural number, i.e positive integers.

In your particular case, the positive integers between (and including) 1 and 100, and then just print them out in a fancy format, which is easy enough:

for (int i = 0; i <= 100; i++)
{
    Console.WriteLine($"0.{i}");
}

P.S the $ before the string signals to C# that this is a interpolated string, they're really cool and useful.

MindSwipe
  • 7,193
  • 24
  • 47
  • The version-sense remark is interesting. It is possible to do `for (var i = new Version(0, 1); i <= new Version(0, 100); i = new Version(0, i.Minor + 1)) { Console.WriteLine(i); }`. Also note that if the asker really needs decimal, you can parse, as in `for (int i = 0; i <= 100; i++) { var dm = decimal.Parse($"0.{i}", CultureInfo.InvariantCulture); Console.WriteLine(dm); }`. The trailing zeros should be maintained, so `0.1` and `0.10` and `0.100` should print differently. – Jeppe Stig Nielsen Oct 19 '22 at 07:18
1
    for (int i = 1; i <= 100; i++)
    {
        Console.WriteLine ("0.{0}",i);
    }
-1

Answering strictly to your question without other assumptions. Just to print the numbers:

for(int i=1;i<=100;i++)
    {
       Console.WriteLine("0."+ (i<10 ? i+"0": i.ToString()));
    }
}
D A
  • 1,724
  • 1
  • 8
  • 19