gpt4 book ai didi

c - 如何打印内部为零的数字?

转载 作者:行者123 更新时间:2023-12-04 12:31:32 26 4
gpt4 key购买 nike

我编写了一个程序来分隔给定数字的数字。当数字由非零组成时它成功分离但是当里面有一个0的数字时,它不识别并且不打印。我应该怎么办?我要疯了!

#include <stdio.h>
#include <conio.h>

int quotient (int a, int b);
int remaindar (int a, int b);

int main(void) {

int a,b,number,temp=1,divisor=10000;

printf("Enter three integers: ");
scanf("%d %d %d",&a,&b,&number);

printf("a/b is %d , remainder is %d.\n",quotient(a,b),remaindar(a,b));

temp=number;

while (temp>=1){

if(temp>=divisor){

printf("%d ", quotient(temp,divisor));
temp=remaindar(temp,divisor);
divisor=divisor/10;
}

else divisor=divisor/10;

}


getch();

return 0;
}

int quotient (int a, int b){

return a/b;

}

int remaindar (int a, int b){

return a%b;

}

最佳答案

根据你的信息:第三个数与商和余数无关。您可以简单地将数字的数字从左到右分开,如下所示:(PS。我假设给定 6900 你期望看到 6,9,0,0)

 #include <iostream>
void getDigits(int number)
{
int div = 1;
//find max divisor, i.e., given 6900, divisor 1000
//this gives information about how may digits the number has
while (number / div >= 10) {
div *= 10;
}

//extract digits from left to right
while (div != 0) //^^pay attention to this condition, not number !=0
{
int currDigit = number /div;
number %= div;
//^^you can change the above two lines to
//your quotient and remainder function calls
div /=10;
std::cout << currDigit << " ";
}
}

int main(){
int number = 6900;
std::cout << "test case 1 " <<std::endl;
getDigits(number);
int number1 = 5067;
std::cout << "\ntest case 2 " <<std::endl;
getDigits(number1);
int number2 = 12345;
std::cout << "\ntest case 3 " <<std::endl;
std::getDigits(number2);
return 0;
}

不要使用 getch(),它已被弃用。使用上面的代码,您可以看到以下输出:

test case 1
6 9 0 0
test case 2
5 0 6 7
test case 3
1 2 3 4 5

关于c - 如何打印内部为零的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16003271/

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