英文:
I'm stuck with this calculator program, I'm not getting the right answer
问题
这是你要的翻译内容:
我的编程课程要求我实现这样的结果:
- 输入第一个数字!
- *9*
- 输入第二个数字!
- *5*
- 9 + 5 = 14
- 9 - 5 = 4
- 9 * 5 = 45
- 9 / 5 = **1.8**,这是个问题,我编写的程序只给我1.0作为答案。我如何让这个数变成1.8而不是1.0?
import java.util.Scanner;
public class Nelilaskin {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("输入第一个数字!");
int first = Integer.valueOf(reader.nextLine());
System.out.println("输入第二个数字!");
int second = Integer.valueOf(reader.nextLine());
int plus = (first + second);
int minus = (first - second);
int multi = (first * second);
double division = (first / (double) second);
System.out.println(first + " + " + second + " = " + plus);
System.out.println(first + " - " + second + " = " + minus);
System.out.println(first + " * " + second + " = " + multi);
System.out.println(first + " / " + second + " = " + division);
}
}
英文:
My programming course wants me to have this kind of endcome:
- Enter the first number!
- 9
- Enter the Second number!
- 5
- 9 + 5 = 14
- 9 - 5 = 4
- 9 * 5 = 45
- 9 / 5 = 1.8 and this is the problem, the program I've written only gives me 1.0 as an answer. How can I get this number to be 1.8 not 1.0?
public class Nelilaskin {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter the first number!");
int first = Integer.valueOf(reader.nextLine());
System.out.println("Enter the second number!");
int second = Integer.valueOf(reader.nextLine());
int plus = (first + second);
int minus = (first - second);
int multi = (first * second);
double division = (first / second * 1.0);
System.out.println(first + " + " + second + " = " + plus);
System.out.println(first + " - " + second + " = " + minus);
System.out.println(first + " * " + second + " = " + multi);
System.out.println(first + " / " + second + " = " + division);
}
}
答案1
得分: 2
请考虑将first和second的数据类型更改为Float。
然后也将结果存储在一个float变量中,那么输出将会符合要求。
float plus = (first + second);
float minus = (first - second);
float multi = (first * second);
float division = first / second;
英文:
Consider replacing the data type for first and second as Float.
And store the resultant in a float variable as well, then the output would be as required.
float plus = (first + second);
float minus = (first - second);
float multi = (first * second);
float division = first / second;
答案2
得分: 1
这是因为你正在对两个整数值进行除法运算,尝试将它们中至少一个转换为双精度类型(double)。
double division = (double)first / (double)second ;
英文:
this is because you are dividing two int values, try to cast at least one of them to double..
double division = (double)first / (double)second ;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论