在第一次循环后没有改变 x 值的情况下进行多次循环?
Having multiple loops without changing x value after first loop?
我不知道这是否真的有意义,但我试图在第二个循环中重用来自 scanf() 的 x 的原始值,以便它可以打印需要打印的内容,但我很难弄清楚。有没有 C 语言的方法(我还是个初学者)不使用函数就可以做到这一点?
int main(){
int x;
int res1 = 0, res2 = 0;
scanf("%u", &x);
//reverse the digits of a number
if (x == 0) {
res2 = 1;
}
while (x != 0) {
if (x % 10 == 0) {
res2++;
x /= 10;
}
else {
x /= 10;
}
}
//count number of zeroes in a number using the same value from the scanf()
do {
res1 = res1 * 10 + x % 10;
x = x / 10;
} while (x != 0);
printf("%u %u\n", res1, res2);
}
要保留 x
的值,您不得更改 x
。 /=
运算符更改左侧操作数的值(除非右侧操作数是 1
)。
试试这个:
int main(){
int x, x_work;
int res1 = 0, res2 = 0;
scanf("%u", &x);
//reverse the digits of a number
if (x == 0) {
res2 = 1;
}
x_work = x;
while (x_work != 0) {
if (x_work % 10 == 0) {
res3++;
x_work /= 10;
}
else {
x_work /= 10;
}
}
//count number of zeroes in a number using the same value from the scanf()
do {
res1 = res1 * 10 + x % 10;
x = x / 10;
} while (x != 0);
printf("%u %u\n", res1, res2);
}
或者您可以简单地删除破坏 x
值的部分,因为 res3
已更改,不会在以后的过程中使用。
int main(){
int x;
int res1 = 0, res2 = 0;
scanf("%u", &x);
//reverse the digits of a number
if (x == 0) {
res2 = 1;
}
//count number of zeroes in a number using the same value from the scanf()
do {
res1 = res1 * 10 + x % 10;
x = x / 10;
} while (x != 0);
printf("%u %u\n", res1, res2);
}
我不知道这是否真的有意义,但我试图在第二个循环中重用来自 scanf() 的 x 的原始值,以便它可以打印需要打印的内容,但我很难弄清楚。有没有 C 语言的方法(我还是个初学者)不使用函数就可以做到这一点?
int main(){
int x;
int res1 = 0, res2 = 0;
scanf("%u", &x);
//reverse the digits of a number
if (x == 0) {
res2 = 1;
}
while (x != 0) {
if (x % 10 == 0) {
res2++;
x /= 10;
}
else {
x /= 10;
}
}
//count number of zeroes in a number using the same value from the scanf()
do {
res1 = res1 * 10 + x % 10;
x = x / 10;
} while (x != 0);
printf("%u %u\n", res1, res2);
}
要保留 x
的值,您不得更改 x
。 /=
运算符更改左侧操作数的值(除非右侧操作数是 1
)。
试试这个:
int main(){
int x, x_work;
int res1 = 0, res2 = 0;
scanf("%u", &x);
//reverse the digits of a number
if (x == 0) {
res2 = 1;
}
x_work = x;
while (x_work != 0) {
if (x_work % 10 == 0) {
res3++;
x_work /= 10;
}
else {
x_work /= 10;
}
}
//count number of zeroes in a number using the same value from the scanf()
do {
res1 = res1 * 10 + x % 10;
x = x / 10;
} while (x != 0);
printf("%u %u\n", res1, res2);
}
或者您可以简单地删除破坏 x
值的部分,因为 res3
已更改,不会在以后的过程中使用。
int main(){
int x;
int res1 = 0, res2 = 0;
scanf("%u", &x);
//reverse the digits of a number
if (x == 0) {
res2 = 1;
}
//count number of zeroes in a number using the same value from the scanf()
do {
res1 = res1 * 10 + x % 10;
x = x / 10;
} while (x != 0);
printf("%u %u\n", res1, res2);
}