[英]How can I print numbers that has zero inside?
我写了一个程序来分隔给定数字的数字。 当数字由非零组成时它成功分离但是当内部有一个数字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;
}
根据您的信息:第3个数字与商和余数无关。 您可以简单地从左到右分隔数字的数字,如下所示:(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
发生这种情况是因为你没有考虑temp小于数字和除数的情况,即数字是0.例如,如果初始数字是302
,则除数是10
,temp是2
,打印出来0
:
while (divisor > 0){
if(temp>=divisor){
printf("%d ", quotient(temp,divisor));
temp=remaindar(temp, divisor);
} else if (temp < number) {
printf("0 ");
}
divisor=divisor/10;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.