gpt4 book ai didi

java - JAVA代码中的不同值

转载 作者:行者123 更新时间:2023-12-02 10:47:04 24 4
gpt4 key购买 nike

我有这段代码,我应该从中获取值:

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
float a=4, b=8 ;
int i=2, j=16 ;
double sol1, sol2, sol3, sol4;
sol1=(a+2*b/j);
sol2=(a/(b-4)+i);
sol3=-(b-i/j);
sol4=(i*a+j/b);
System.out.println(sol1);
System.out.println(sol2);
System.out.println(sol3);
System.out.println(sol4);
}
}

And here is a Java fiddle of the solution :

5
3
-8
10

但是在sol3中,我计算出的值不是-8,而是-7.875,所以为什么它取-8.0。

我尝试将sol3单独分解为单独执行like in this fiddle :

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
float a=4, b=8 ;
int i=2, j=16 ;
double sol1, sol2, sol3, sol4;

sol1=-i/j;
sol2=b+sol1;
sol3 = -sol2;
System.out.println(sol1);
System.out.println(sol2);
System.out.println(sol3);

}
}

仍然给我-8.0,在计算器上是-7.875。我知道太简单了,但我不明白为什么?

最佳答案

sol1=-i/j;

的计算结果为 0,因为 i < j 并且它们都是 int。将其中之一更改为 float 或 double 以执行浮点除法。

关于java - JAVA代码中的不同值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35030982/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com