尝试使用java计算百分比
所以我试图创建一个java程序,它将生成一个学生的20个随机活动。然后计算他们这样做的百分比。例如:尝试使用java计算百分比,java,Java,所以我试图创建一个java程序,它将生成一个学生的20个随机活动。然后计算他们这样做的百分比。例如: for(int i = 1; i <= 20; i++); { System.out.println("ouch"); } 40%的时间睡觉 步行30%的时间 课堂上30%的时间 但我的百分之零点三个选项,但只有一个5% app.java public class app { /** * @param args the command line
for(int i = 1; i <= 20; i++); {
System.out.println("ouch");
}
40%的时间睡觉步行30%的时间
课堂上30%的时间 但我的百分之零点三个选项,但只有一个5% app.java
public class app {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String initName = "John";
String lastName = "Smith";
int age = 20;
double stcount = 0;
double slcount = 0;
double clcount = 0;
double wkcount = 0;
student st1 = new student(initName, lastName, age);
for (int i = 1; i <= 20; i++);
{
String activity = st1.whatsUp1();
System.out.print(1 + " ");
System.out.println(st1.whatsUp1());
if (activity.equals(" studying")) {
stcount++;
}
if (activity.equals(" sleeping")) {
slcount++;
}
if (activity.equals(" in class")) {
clcount++;
}
if (activity.equals(" walking")) {
wkcount++;
}
}
System.out.println(" ");
System.out.println(stcount++ / 20 * 100 + "% " + "of the time the student is studying");
System.out.println(slcount++ / 20 * 100 + "% " + "of the time the student is reading");
System.out.println(clcount++ / 20 * 100 + "% " + "of the time the student is walking");
System.out.println(wkcount++ / 20 * 100 + "% " + "of the time the student is in class");
}
}
错误在以下几行中:
System.out.println(stcount++/20 * 100 + "% "+ "of the time the student is studying");
罪魁祸首是整数除法:stcount是一个整数,您将它除以20,它也是一个整数。Java随后将生成一个变量,该变量也是一个整数。它是通过去掉小数部分来实现的,例如,如果stcount是10,那么它将执行10/20=0.5,这将变成0!您需要通过使用浮点除法来确保它不会变成一个整数,只需确保这两个除法中的一个是浮点:
stcount++/20.0
要么在整数20的末尾加一个.0,要么在它的末尾加一个“d”
你有这个
System.out.println(stcount++/20 * 100 + "% "+ "of the time the student is studying");
你也可以
System.out.println(stcount++/20.0 * 100 + "% "+ "of the time the student is studying");
或
你的错误在这行
for (int i = 1; i <= 20; i++);
这段代码看起来像打印了20次ouch,但实际上只打印了一次,因为它相当于:
for(int i = 1; i <= 20; i++) {
};
{
System.out.println("ouch");
}
for(int i=1;i行System.out.println(st1.whatsUp1());
通常会产生不同于活动中实际存储为whatsUp1()的结果总是会产生一些随机结果…为什么要在println中递增stcount
,等等。据我所知,递增的值从未使用过。double test=0;test++;System.out.println(test++/20*100);这是完全错误的,java对从左到右的每一个两两计算都使用最大的类型,这意味着整个计算都是双精度的,只要stcount是最左边的成员。上面的程序片段证明,因为它输出5.0你是对的,所以stcount是双精度的。++让我措手不及。那么问题是什么呢?t循环后的分号表示好眼力!为愚蠢的语法错误检测器升级OP为什么要这样做?你认为它的优势在哪里?
for(int i = 1; i <= 20; i++); {
System.out.println("ouch");
}
for(int i = 1; i <= 20; i++) {
};
{
System.out.println("ouch");
}