英文:
The loop runs, The (Modoule) in if else than it gives me error
问题
[此图像无法正常工作](https://i.stack.imgur.com/B1bYT.png)
public class file {
public static void main(String[] args) {
for (double i = 1; i < 50; i++){
System.out.println(i);
double x = 1000;
x = (x/i);
System.out.println(x);
if(x % 2){
System.out.println("数字是偶数" + x);
}
else{
System.out.println("数字是奇数" + x);
}
}
}
}
这个循环对我来说有效,但当我尝试在if else中添加(Modoule)时,它会给我一个错误。我期望运行if和else并给我偶数和奇数。
英文:
[This image does not work](https://i.stack.imgur.com/B1bYT.png)
public class file {
public static void main(String[] args) {
for (double i = 1; i < 50; i++){
System.out.println(i);
double x = 1000;
x = (x/i);
System.out.println(x);
if(x % 2){
System.out.println("The number is even" + x);
}
else{
System.out.println("The number is odd" + x);
}
}}}
The number is even1.2765957446808507 48.0
20.833333333333332
The number is even0.8333333 33333321
49.0
20.408163265306122
The number is even0.408163265306122 PS C:\Users\Amrit>
& 'C:\Users\Amrit\AppData\Local\Programs\Eclipse Adoptium\j dk-17.0.7.7-hotspot\bin\java.exe' '-XX:+ShowCodeDetailsInExceptionMessages' '-c
p' 'C:\Users\Amrit\AppData\Local\Temp\vscodesws_db8f8\jdt_ws\jdt.ls-java-projec t\bin'
'file'
Exception in thread "main" java.lang.Error: Unresolved compilation problem: Type mismatch: cannot convert from double to boolean
at file.main(file.java:9)
PS C:\Users\Amrit> ||
Text courtesy of imagetotext.info
The loop works for me, but when I try to add (Modoule) in if else than it gives me error. I was expecting to run if and else and give me even odd numbers
答案1
得分: 1
if (x % 2) {
无法工作,因为 `x` 是一个 double,所以 `x % 2` 不是 `if` 期望的布尔值。与 C 不同,Java 不会自动转换它。
if (x % 2 == 0) {
将有效,但大多数情况下,测试 double 的相等性会引发问题,因为它们用于测量等会丢失精度的事物。通常情况下,您应该测试它们是否小于某个 epsilon 值。我唯一想到的良好理由是测试它是否正确加载或保存。
模除运算在整数上更常见。
还有,请修复您的缩进,以使代码的末尾不像丑陋的鱼鳃。
英文:
if(x % 2){
Doesn't work because x
is a double and so x % 2
isn't the boolean the if
expected. Unlike c, java wont convert that for you.
if (x % 2 == 0) {
Will work but it sets my teeth on edge because most of the time you shouldn't test a double's equality since they are used for lossy things like measurements. Typically you test them to be less then some epsilon value. Only good excuse I've ever thought of is to test if it was loaded or saved correctly.
Modular division is more typically used on integers anyway.
Oh and fix your indentation so the end of your code doesn't look like an ugly fish gill.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论