Home > database >  Can't get the variable to do an operation inside a for
Can't get the variable to do an operation inside a for

Time:03-20

I'm new on Java using NetBeans and I was requested to do the next op:enter image description here showing the results of each op in a separate row but I cant get the results of the op, also I was requested to use 2 methods that's why I did it like that. Thank you.

package Ex;
import java.util.Scanner;

public class Ex3 {

static int n;
static double r;
static Scanner in = new Scanner(System.in);

public static void main(String[] args) {
    Recolec();
    Pol();
}
public static double Recolec() {
System.out.println("Enter desired variable: ");
    n=in.nextInt();
    return r;
}
public static double Pol (){
    for (int i = 1; i <= 5; i   ){
        r=((1/i)*(Math.pow((n-1)/n, i)));

        System.out.println("Value"   i   ": "  r);
    }
    return r;
  } 
}

Output:

Enter desired variable: 5
Value1: 0.0
Value2: 0.0
Value3: 0.0
Value4: 0.0
Value5: 0.0

CodePudding user response:

change formula like this r = ((1D / i) * (Math.pow((n - 1D) / n, i)));

CodePudding user response:

You are currently doing integer division when you use 1/i because both 1 and i are integers. This means that the answer gets rounded down (meaning 11/10 = 1 or 7/10 = 0 etc). If you want an answer with more precision you can turn one of the variables into a double. That can be done with: 1D/i, where D means that the 1 is a double (altenatively, you can use 1f/i if you want a float). Or you can write 1.0/i. You have the same problem in the division (n-1)/n as well. Changing it to (n-1.0)/n should work.

I saw your comment about what 1D does but couldn't answer because don't have reputation :/

  • Related