I'm sorry if this is a duplicate but I haven't found anything relevant to it.
So, how can I print 0
for the numbers having a whole square root with the following code?
for (n = 1.0; n <= 10; n++)
{
Console.WriteLine ("Fractional Part : {0 :#.####}", (Math.Sqrt(n) - (int) Math.Sqrt(n)));
}
Current O/P:
In chemistry, the whole number rule states that the masses of the isotopes are whole number multiples of the mass of the hydrogen atom. The rule is a modified version of Prout's hypothesis proposed in 1815, to the effect that atomic weights are multiples of the weight of the hydrogen atom.
Python Create List from 0 to 100. A special situation arises if you want to create a list from 0 to 100 (included). In this case, you simply use the list(range(0, 101)) function call.
Assuming a leading zero on the other fractional results is acceptable, and since your result is always in the range of [0,1)
, you could just change #.####
to 0.####
.
for (var n = 1.0; n <= 10; n++)
{
Console.WriteLine("Fractional Part : {0:0.####}", (Math.Sqrt(n) - (int) Math.Sqrt(n)));
}
Results:
Fractional Part : 0
Fractional Part : 0.4142
Fractional Part : 0.7321
Fractional Part : 0
Fractional Part : 0.2361
How about using The numeric "N"
format specifier with 4
precision?
for (var n = 1.0; n <= 10; n++)
{
Console.WriteLine("Fractional Part : {0}",
(Math.Sqrt(n) - (int)Math.Sqrt(n)).ToString("N4"));
}
Result is:
Fractional Part : 0.0000
Fractional Part : 0.4142
Fractional Part : 0.7321
Fractional Part : 0.0000
Fractional Part : 0.2361
Fractional Part : 0.4495
Fractional Part : 0.6458
Fractional Part : 0.8284
Fractional Part : 0.0000
Fractional Part : 0.1623
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With