I am trying to implement a basic calculation. The program take in 2 numbers, it works fine with 10 divided by 5 and give answer 2. If any smaller value divided by a larger value it will give me 0, can I have the answer in fraction?
Example 8 divided by 100 equal 8/100 rather than 0.
public class numtheory {
public static void main(String[] args) {
int n1;
int n2;
Scanner scan = new Scanner(System. in );
System.out.println("input number 1: ");
n1 = scan.nextInt();
System.out.println("input number 2: ");
n2 = scan.nextInt();
int temp1 = n1 / n2;
System.out.print("\n Output :\n");
System.out.print(temp1);
System.exit(0);
}
}
You need to convert your numbers to double:
double temp = ((double) n1) / n2;
If you want to produce a fraction, you can just print out:
System.out.println(n1 + "/" + n2);
This will print out whatever numbers you're given though, they won't be reduced.
You can reduce them yourself however with something like:
int n = n1;
int d = n2;
while (d != 0) {
int t = d;
d = n % d;
n = t;
}
int gcd = n;
n1 /= gcd;
n2 /= gcd;
And then print them out:
System.out.println(n1 + "/" + n2);
Instead of using integers, you need to use double.
This because an integer can only contain while numbers where double can contain decimal numbers.
u could change all the int to double or cast the in to double by dooing
((double) yourIntValue)
you could also get the input as a string, and parse it with
double dval=Double.parseDouble(value);
Related
I need to display the correct arithmetic average of a series of integers entered by the user.
If the user enters 6, 9, 7, and 4, the average should be 6.5 but instead displays 6.0. Why does that happen? I used an ArrayList to store all the integers.
import java.util.Scanner;
import java.util.*;
import java.util.Collections;
public class QuizScoreStatistics
{
public static void main(String[] args) {
List<Integer> Scores = new ArrayList<Integer>();
Scanner input = new Scanner(System.in);
int i = 0;
int a = 0;
while(a != 99) {
System.out.println("Enter scores");
a = input.nextInt();
if(a != 99) {
if ( a > 10 || a < 0) {
System.out.println("Score must be between 10 and 0");
}
else {
Scores.add(a);
}
i++;
}
}
int max = Collections.max(Scores);
int min = Collections.min(Scores);
int sum = 0;
double averg = 0;
for( i = 0; i <= Scores.size() - 1; i++) {
sum += Scores.get(i);
}
averg = sum / Scores.size();
System.out.println("Scores entered " + i);
System.out.println("Highest score " + max);
System.out.println("Lowest score "+ min);
System.out.println("Average: "+ averg);
}
}
I won't try to give away the entire question I think you could probably answer that yourself given a nudge in the right direction.
You correctly identified that your averg is a double because your answer could come out to something like 6.7 or 2.3 or whatever. Thats a correct assumption to make! However during your "arithmetic process" you are using integers to do the division, which will come out as an integer. I will repeat the actual DIVISION is happening with two integers , can you see where the bug is coming from?
If you need more of a push to see the exact remedy of this solution I would point you here
https://programming.guide/java/wrong-results-for-division.html
Try averg = (1.0 *sum) / Scores.size(); because int/int => int but double/int=>double
Ok, this is how the operator "/" works.
int / int => int
int / float => float
float / int => float
Since you are doing an int division (int/int), the result will be an int, losing decimal information. If you want your division to be float or double, you have two options, either you declare the sum as double or you can just cast the division, so it becomes a double division instead of an int division.
averg = (double) sum / Scores.size();
I have the following problem:
If n1 & n2 are natural numbers while n1 < 10 and n2 <10000.
find the summation of all digits in z where z = n1n2.
ex. n1 = 3, n2 = 10, z= 3^10 = 59049 if you sum the digits 5+9+0+4+9= 27. result =27
ex. n1 = 2, n2 = 12, z= 2^12 = 4096 if you sum the digits 4+0+9+6 = 19. result =19
And my current solution is:
public static long Solving(int n1, int n2) {
if (n1 >= 0 && n2 >= 0) {
BigInteger z = BigInteger.valueOf((long) Math.pow(n1, n2));
long sum = 0;
for (BigInteger i = z; i.compareTo(BigInteger.ZERO) > 0; i = i.divide(BigInteger.TEN)) {
sum += Integer.valueOf(String.valueOf(i.remainder(BigInteger.TEN)));
}
return sum;
}
return 0;
}
Why all cases doesn't success in that problem?
The actual problem is Math.pow(n1, n2).
Here you are treating both arguments as double and trying to calculate n1n2 which can easily cause an overflow.
Instead you can use BigInteger#pow() to get rid of overflow:
BigInteger z = BigInteger.valueOf(n1).pow(n2);
This will solve the issue.
I think you can solve this easily by doing something like this :
Step 1. Convert n1 to BigInteger
Step 2. Use native power function of BigInteger [exponent of pow function of big integer must be int]
Step 3. Convert the result back into string
Step 4. Iterate over the string and calculate the sum of digits.
Reference : https://www.tutorialspoint.com/java/math/java_math_biginteger.htm
https://www.tutorialspoint.com/java/math/biginteger_pow.htm
//java program that asks the user to input a number that e^x=1+x+x^2/2! +x^3/3!... e is a mathematical constant equal to 2.718...
import java.util.Scanner;
public class taylor_2 {
public static void main(String args[]) {
Scanner input=new Scanner(System.in);
double x; //input for x
double factorial=1; //initializes factorial
int counter=1; //initializes counter
double result=1; //initializes result
System.out.println("Enter non negative number"); //asks user to enter x
x=input.nextInt();
//output in while loop will continue to be generated if user doesn't entered a negative number
while(x<1){
System.out.println("I said entered a positive number");
x=input.nextInt();
}
while(x>counter){
factorial=factorial*counter;//factorial formula
result=result+(Math.pow(x,counter))/factorial; //equation for e^x=1+x+x^2/2! +x^3/3!
counter++;
}
System.out.println("Taylor series is " +result);//output for taylor equation e^x
}
}
Here is the output of my code:
Enter non negative number
2
Taylor series is 4.0
When I entered 2 , it should have outputted 7.3890560983 instead of 4.0 since e=2.718... and e^2=7.3890560983. What am I doing wrong?
The problem is that the Taylor series is not the same function that e^x.
It will return a function that is close to the function e^x.
For understanding it better, I recommend you to look the second picture of the next link:
https://en.wikipedia.org/wiki/Taylor_series
You can see in the previous picture that as n is getting larger the function is getting more accurate.
Your code's problem is that your x value is your n value, and this is not really true.
x: Must be the value you want to now e^x.
n: Is the accurate of your equation. Larger means more accurate.
So you must change while(x>counter) with while(n>counter), where n can be either a variable with the user selected accuracy, or a constant with your selected accurcy.
I think that until x=100, n=150 should work.
I hope that helps you! :)
There seems to be an answer here: EXP to Taylor series for c++, even though the algorithm is slightly different to yours. Here's its Java version:
public class TaylorSeries {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter x:");
double x = input.nextDouble();
double result = calcExp(x);
System.out.println("calcExp(x) = " + result);
System.out.println(" e^x = " + Math.pow(Math.E, x));
}
static double calcExp(double x) {
double eps = 0.0000000000000000001;
double elem = 1.0;
double sum = 0.0;
boolean negative = false;
int i = 1;
sum = 0.0;
if (x < 0) {
negative = true;
x = -x;
}
do {
sum += elem;
elem *= x / i;
i++;
if (sum > Double.MAX_VALUE) {
System.out.println("Too Large");
break;
}
}
while (elem >= eps);
return negative ? 1.0 / sum : sum;
}
}
The output:
Enter x:
2
calcExp(x) = 7.389056098930649
e^x = 7.3890560989306495
All credit should go to the answer here: EXP to Taylor series. I have only converted c++ code to Java
Is there an exponential operator in Java?
For example, if a user is prompted to enter two numbers and they enter 3 and 2, the correct answer would be 9.
import java.util.Scanner;
public class Exponentiation {
public static double powerOf (double p) {
double pCubed;
pCubed = p*p;
return (pCubed);
}
public static void main (String [] args) {
Scanner in = new Scanner (System.in);
double num = 2.0;
double cube;
System.out.print ("Please put two numbers: ");
num = in.nextInt();
cube = powerOf(num);
System.out.println (cube);
}
}
There is no operator, but there is a method.
Math.pow(2, 3) // 8.0
Math.pow(3, 2) // 9.0
FYI, a common mistake is to assume 2 ^ 3 is 2 to the 3rd power. It is not. The caret is a valid operator in Java (and similar languages), but it is binary xor.
To do this with user input:
public static void getPow(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter first integer: "); // 3
int first = sc.nextInt();
System.out.println("Enter second integer: "); // 2
int second = sc.nextInt();
System.out.println(first + " to the power of " + second + " is " +
(int) Math.pow(first, second)); // outputs 9
The easiest way is to use Math library.
Use Math.pow(a, b) and the result will be a^b
If you want to do it yourself, you have to use for-loop
// Works only for b >= 1
public static double myPow(double a, int b){
double res =1;
for (int i = 0; i < b; i++) {
res *= a;
}
return res;
}
Using:
double base = 2;
int exp = 3;
double whatIWantToKnow = myPow(2, 3);
There is the Math.pow(double a, double b) method. Note that it returns a double, you will have to cast it to an int like (int)Math.pow(double a, double b).
you can use the pow method from the Math class. The following code will output 2 raised to 3 (8)
System.out.println(Math.pow(2, 3));
In case if anyone wants to create there own exponential function using recursion, below is for your reference.
public static double power(double value, double p) {
if (p <= 0)
return 1;
return value * power(value, p - 1);
}
This program is supposed to get a Fibonacci number from the user and the program will calculate what it is while making sure that the user entered a positive number and a number no less than the Fibonacci number 70. So, if the user entered 7, it should print 13. The method fibcalc() is supposed to do the calculations.
When I try and compile the program, I get the errors "method fibcalc in class Fibonacci cannot be applied to given types: System.out.printf("Fibonacci #%d is %f", num, fibcalc(num, x3)); and "cannot find symbol" return x3;Here's my code:
import java.util.Scanner;
public class Fibonacci
{
public static void main ( String args[] )
{
Scanner input = new Scanner ( System.in );
int num;
double x3 = 0;
System.out.print("Which Fibonacci number would you like? ");
num = input.nextInt();
do
{
System.out.print("Which Fibonacci number would you like? ");
num = input.nextInt();
}while(num >= 0 && num <= 70);
System.out.printf("Fibonacci #%d is %f", num, fibcalc(num, x3));
}
public static double fibcalc(int num)
{
int x1 = 0;
int x2 = 1;
if (num == 0)
return 0;
else if (num == 1)
return 1;
else
for (int x3 = 0; x3 < num; x3++)
{
x3 = x1 + x2;
x1 = x2;
x2 = x3;
}
return x3;
}
}
There are probably other problems I've missed. I'm pretty new to java. Thanks in advance.
The fibcalc() method has a single int parameter, but you are calling it with two parameters.
Change the call from
fibcalc(num, x3)
to
fibcalc(num)
ie change that line to:
System.out.printf("Fibonacci #%d is %f", num, fibcalc(num));
Also, if you want accurate numbers for your results, change from using double to using BigInteger, which can handle arbitrarily large numbers accurately.
You can also use the following calculator to calculate the Fibonacci sequence (using Javascript): enter link description here
If you want to compute Fibonacci numbers, you can use direct (non-recursive, non-iterative) formula for Fibonacci numbers:
Fib(n) = (pow((1+sqrt(5))/2, n) + pow((1-sqrt(5))/2, n)) / sqrt(5)
It turns out that for all n >= 0, you can simplify this formula to:
Fib(n) = round(pow((1+sqrt(5))/2, n) / sqrt(5))
Knowing this, you can use following simple implementation for fibcalc:
public static double fibcalc(int num) {
return Math.floor(Math.pow((1+Math.sqrt(5))/2, num) / Math.sqrt(5) + 0.5);
}