Quote (Trig @ Mar 19 2013 07:41pm)
I'm trying to code it so it asks the question "What is the power of (number) raised to the power of (2)"
**** this is a intro to programming class *****
I set the power to = 2, but for some reason, it gives me like 16.0 or 25.0; here is my code..
power is set as an int
number is set as an int
System.out.println(" You are now veiwing a sample test question");
number = (int)(Math.random() * 10);
power = Math.pow(number, 2);
System.out.println("What is the answer of the number " + number + (" raised to the power of ") + power);
if (number * power == yourAnswer)
{
System.out.println(" You are correct!");
}
else
{
System.out.println("You are wrong!");
}
multiple flaws mixed with unclear questions is no way to get help, so i will be taking stabs in the dark.
if you want to remove your decimal places cast your answer as (int), although if this were C (which its not) the compiler should have yelled at you that you are supplying ints to a double function without a cast.
as for your if statement there are two ways to fix this. one, you can simply use the exp() or pow() functions located in your math class, or two, loop power times and during each loop multiple the number by itself as so.
Code
int answer;
for(int i = 0; i < power; i++)
{
answer *= number
}
if(answer == youranswer)
{
//correct
}else {
//incorrect
}
simplest way is to use the pow function inside the if statement like so.
Code
if((int)Math.pow(number, power) == youranswer)
This post was edited by AbDuCt on Mar 19 2013 08:56pm