我的程序应该根据数字的位数打印出星号。这是应该发生的事情:


  
  输入:24 ||输出:2 ** 4 ****
  输入:24000 ||输出:2 ** 4 **** 0 0 0
  


这是我的代码:

void histogram (){
int nNum, nCount, nMult, nTemp=-1, n;
printf("Please input a value: ");
scanf("%d", &nNum);
n=nNum;
do{
    nCount = 0;
    nMult = 1;
    while(n>0){
        n /= 10;
        nCount++;
    }
    while(nCount>1){
        nMult *= 10;
        nCount--;
    }
    nTemp = nNum / nMult;
    printf("%d ", nTemp);
    do{
        printf("*");nTemp--;
    }while(nTemp>0);
    printf("\n");
    nNum%=nMult;
    n = nNum;
}while(n>0);}


我的代码没有打印出尾随的零,我希望你们能帮我这个忙。谢谢!

最佳答案

最好使此类函数递归。它允许保持尾随零。

这是一个示范节目

#include <stdio.h>

void histogram( unsigned int n )
{
    const unsigned int Base = 10;
    const char c = '*';

    unsigned int digit = n % Base;

    if ( n /= Base ) histogram( n );

    printf( "%u ", digit );
    for ( ; digit != 0; --digit ) printf( "%c ", c );
}

int main(void)
{
    while ( 1 )
    {
        unsigned int n;

        printf( "Please input a non-negative value (0 - exit): " );

        if ( scanf( "%u", &n ) != 1 || n == 0 ) break;

        printf( "\n" );

        histogram( n );

        printf( "\n" );
    }

    return 0;
}


程序输出可能如下所示

Please input a non-negative value (0 - exit): 123456789

1 * 2 * * 3 * * * 4 * * * * 5 * * * * * 6 * * * * * * 7 * * * * * * * 8 * * * * * * * * 9 * * * * * * * * *
Please input a non-negative value (0 - exit): 24000

2 * * 4 * * * * 0 0 0
Please input a non-negative value (0 - exit): 0


至于您的方法,则在反转数字时必须计算尾随零。

关于c - 根据数字的每个数字打印出星号,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40693274/

10-09 05:35
查看更多