如何计算将整个输入作为字符串的计算器中的百分比?(How to calculate percentage in a calculator that takes whole input as a String?)
public static int applyOp(char op, int b, int a) {
switch (op) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '%':
return a % b; //But this doesn't work properly.
case '/':
if (b == 0)
throw new
UnsupportedOperationException("Cannot divide by zero");
return a / b;
}
return 0;
}
}
我尝试过使用100 * 10 + 2,525 + 5%,525 * 5%,但其他操作符正常工作,但'%'没有。
public static int applyOp(char op, int b, int a) { switch (op) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '%': return a % b; //But this doesn't work properly. case '/': if (b == 0) throw new UnsupportedOperationException("Cannot divide by zero"); return a / b; } return 0; } }i tried this using 100*10+2, 525+5%, 525*5% but other operators work properly but '%' doesn't.
最满意答案
public static int applyOp(char op, int b, int a) { switch (op) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '%': return (int)(((float) a / b) * 100); case '/': if (b == 0) throw new UnsupportedOperationException("Cannot divide by zero"); return a / b; } return 0; } }当使用% ,它将返回除法a的modulus [余数]乘以b
public static int applyOp(char op, int b, int a) { switch (op) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '%': return (int)(((float) a / b) * 100); case '/': if (b == 0) throw new UnsupportedOperationException("Cannot divide by zero"); return a / b; } return 0; } }while using % it will return the modulus [remainder] for the division a by b
更多推荐
发布评论