我写了一个程序来分隔给定数字的数字。当数字由非零组成时它成功分离但是当内部有一个数字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;
}
答案 0 :(得分:1)
根据您的信息:第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
答案 1 :(得分:1)
这种情况正在发生,因为您没有考虑temp小于数字和除数的情况,即数字是0.例如,如果初始数字是302
,则除数为{ {1}}和temp为10
,打印出2
:
0