我有这个程序在解析的int中找到奇数和偶数的总和,如下所示。我的程序现在正在寻找从右到左的总和。我如何制作它从最后一位数字(即从左到右)开始呢?
out.print("Please enter a number: ");
String s = in.nextLine();
int x = Integer.parseInt(s);
int y = 0;
int e = 0;
int o = 0;
while (x != 0) {
y = x % 10;
out.print(y + " ");
if (y % 2 == 0) {
e = e + y;
out.print(e + " ");
} else {
o = o + y;
out.print(o + " ");
}
x = x / 10;
}
out.println("sum of odd: " + o);
out.println("sum of even: " + e);
我在无限循环中运行
out.print("Please enter a number: ");
String s = in.nextLine();
double x = Integer.parseInt(s);
double y = 0;
double e = 0;
double o = 0;
double length = Math.pow(10, s.length() - 1);
while (x != 0) {
y = x / length;
if (y % 2 == 0) {
e = e + y;
} else {
o = o + y;
}
x = x % length;
}
out.println("sum of odd: " + o);
out.println("sum of even: " + e);
答案 0 :(得分:1)
你可以改变你的分工方式。也许你的循环看起来像这样:
// Figure out how many digits you have. I'll leave that to you
int digits = ...;
for(int i = digits; i < 0; i--) {
int currentDigit = (x / Math.exp(10, i-1)) % 10;
// You have your digit, so the checking/summing happens here.
}
例如,如果您的数字为1234.它有4位数,所以循环的第一次迭代,i = 4.因此,表达式变为:
int currentDigit = (1234 / 1000) % 10;
产生的结果1.第二次迭代是:
int currentDigit = (1234 / 100) % 10;
哪个产生2.分割截断你不想看到的数字的右边,模数截断了你不想看到的左边。