gpt4 book ai didi

java - 除以零简单程序

转载 作者:行者123 更新时间:2023-12-01 22:25:51 26 4
gpt4 key购买 nike

 public static void main(String [] args) {

Scanner userInput = new Scanner(System.in);

int myCents = 0;
int myDollars = 0;
int myQuarters = 0;
int myDimes = 0;
int myNickels = 0;
int myPennies = 0;

System.out.printf("Please enter the amount of cents below: \n");
myCents = userInput.nextInt();

myDollars = myCents/100;
myQuarters = myCents % myDollars;
myDimes = myCents % myQuarters;
myNickels = myCents % myDimes;
myPennies = myCents % myNickels;

System.out.printf(myCents + " is equal to %4d", myDollars);
System.out.printf(" dollar(s), " + myQuarters);
System.out.printf(" quarter(s), " + myDimes);
System.out.printf(" dime(s), " + myNickels);
System.out.printf(" nickel(s) and " + myPennies + " pennies. \n");
}
}
Error: java.lang.ArithmeticException: / by zero

错误似乎不断出现。到目前为止我们还没有学习 Java 的 if 语句。它应该是一个简单的程序。

最佳答案

myCents/100是整数除法,所以如果 myCents < 100 , myDollars将是 0。 着火 % myDollars会扔你的/ by zero异常。

尝试:

myDollars = myCents / 100;
myCents = myCents % 100;
myQuarters = myCents / 25;
myCents = myCents%25;

等等。 (假设 25 美分是 25 美分...我从未使用过美元)

关于java - 除以零简单程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28796339/

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