Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Creating a program that can take an exponent and base and give answer.

$
0
0
Hi, here is a picture of the instructions exactly: http://imgur.com/LCPLWGx

For those who do not trust link I need to create a program that creates a MyMath class and within that class takes a given double and int (base and exponent respectively) and find the answer.

Here is my MyMath.java code:
public class MyMath 
{
		public static double myPow(double base, int exponent)
		{
		if (base == 0.0 && exponent == 0)
		{
			System.out.println("Please enter acceptable values.");
			System.exit(1);
		}
		else if (base != 0.0 && exponent == 0)
		{
			return 1.0;
		}
		else if(base != 0.0 && exponent > 0)
		{
			for(int i = 0; i <= exponent; i++)
			{
				base *= exponent;
			}
			return base;
		}
		else if(base != 0.0 && exponent < 0)
		{
			for(int i = 0; i <= exponent; i++)
			{
				base = (1 / base);
				base *= exponent;
			}
			return base;
		}
		base = base * 0.5;
		return base;
	}
}



Then here is my Main.java:
import java.util.Scanner;
public class Main 
{
	
	private static Scanner kb;
	public static void main (String args[])
	{
		kb = new Scanner(System.in);
		System.out.println("Enter a number with up to one decimal that is not 0:");
		double base = kb.nextDouble();
		System.out.println("Enter a number with no decimals that is not 0:");
		int exponent = kb.nextInt();
		System.out.println("Answer: " + MyMath.myPow(base, exponent));
	}
}



Having a few problems:
  • When I enter a base with a positive exponent it will multply an extra 2 times. Example: 2 raised to the 2 will give me 16.
  • Next problem is that when there is a negative exponent it just gives back the number. Example: When base is 2 and exponent is -2 I get 2 back rather than 1/4.
  • As of right now currently making exponent 0 will correctly give 1 and if both of the values are 0 it will correctly ask the user to input correct values.

Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>