3

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

#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;

}
4

2 回答 2

1

根据您的信息:第三个数字与商和余数无关。您可以简单地将数字的数字从左到右分开,如下所示:(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
于 2013-04-14T19:51:22.353 回答
1

发生这种情况是因为您没有考虑 temp 小于数字和除数的情况,即数字是 0。例如,如果初始数字是302,除数是10并且 temp 是2,打印出 a 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;
}   
于 2013-04-14T19:54:06.953 回答