user3281855
user3281855

Reputation: 11

how do I print a number less than 1 but greater than 0?

I am expressing the power method in a script, at one point I am trying to do a negative, which is 1 / final_answer

the thing is it does not print things such as 2^-3 which is .125

using System;

class MainClass
{
static void Main()
{
    Console.Write ("Enter a base number: ");
    string str_x = Console.ReadLine ();
    double x = double.Parse (str_x);

    Console.Write ("Enter an exponent: ");
    string str_n = Console.ReadLine ();
    double n = double.Parse (str_n);

    double final = 1;
    int count = 1;
    while (count != n+1) {
        final = final * x;
        count++;
    }
    if (n < 0)
        final = 1 / final;


    Console.WriteLine(final);
}

}

Upvotes: 1

Views: 355

Answers (2)

AlexD
AlexD

Reputation: 32576

First of all, the loop

int count = 1;
while (count != n + 1)
    final = final * x;
    count++;
}

cannot end if n == -3 since count is always positive.

In addition, it could be an endless loop because you compare int and double

double n = float.Parse (str_n);
....
int count = 1;
while (count != n + 1) {

You should avoid use of == and != with doubles.

Upvotes: 2

TypeIA
TypeIA

Reputation: 17258

With negative values of the exponent, your loop never terminates because count will never reach a negative value (or zero), at least until it overflows.

And as others said, read the exponent as an integer, not a double.

Upvotes: 0

Related Questions