简体   繁体   中英

Java- Passing a variable to the end of a number

I'm trying to figure out how to pass in a variable into random parts of a math problem. This is a simple example of my problem

public class EquationY {

public static void main(String[] args) {

     double x = 5;

double y = 4.6x + 34.2 ;

 System.out.println("y is " + y);
}

}

All I need to do is change the x to a 5 so it will read 4.65 + 34.2


For any of you that might not be fed up with me yet, let me know if this code is acceptable or should I start looking to find an easier way

12.3x^4 - 9.1x^3 + 19.3x^2 - 4.6x + 34.2

public static void main(String[] args) {

     double x = 5;

double y = Math.pow(12.3 + x/100, 4) - Math.pow(9.1 + x/100, 3) + Math.pow(19.3 + x/100, 2) - (4.6 + x/100) + 34.2 ;

 System.out.println("y is " + y);
}

y is 22901.02463125001

Assuming that you're trying to take a number and insert it to any location within any value in an equation, you probably should be treating all the values in the equation as strings. Then you can perform the insert easily and convert all the values to doubles afterwords.

Use the following code

public static void main(String[] args) {

    double x = 5;

    String z = 4.6 + String.valueOf((int)x);
    double y = Double.parseDouble(z) + 34.2 ;
    System.out.println("y is " + y);
}

This will give the answer you wanted.

you can do this way

double x=0.05;
double y = (4.6+x) + 34.2 ;
 double x = 0.05;
 double y = (4.6 + x) + 34.2 ;

instead of

 double x = 5;
 double y = 4.6x + 34.2 ;

Try

public static void main(String[] args) {

        double x = 0.05;

        double y = (4.6 + x) + 34.2;

        System.out.println("y is " + y);

    }

output:

 y is 38.85

Without changing x value

public static void main(String[] args) {

    double x = 5;

    double y = (4.6 + x/100) + 34.2;

    System.out.println("y is " + y);

}

output:

y is 38.85

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM