Home > Blockchain >  How can I display the given number with the corresponding commas in place?
How can I display the given number with the corresponding commas in place?

Time:11-30

#include<stdio.h>
int getDivisorForLeftmostDigit(int nVal)
{
    int nDiv=1;
    if(nVal<0)
        nVal *= -1; //just to be sure
    {
        nDiv*=10;
        nVal/=10;
    }
    return nDiv;
}

int getNumberOfDigits(int nVal)
{
    int nCnt=0;
    if(nVal<0)
        nVal *= -1; //just to be sure
    {
        nCnt  ;
        nVal/=10;
    }
    return nCnt;
}

void displayWithComma(int nVal)
{
    int nCnt=getNumberOfDigits(nVal);
    int nMult = getDivisorForLeftmostDigit(nVal);

    if(nVal<0)
    {
        printf("-");
        nVal*=-1;
    }

    while(nCnt>0)
    {
        printf("%d", nVal/nMult);
        if(nCnt>1 && nCnt%3==1)
            printf(",");
        nMult/=10;

        nCnt--;
    }
    printf("\n");
}

int main()
{
    displayWithComma(-23);
    displayWithComma(27369);
    displayWithComma(-1238246);
    return 0;
}

`

I feel like I'm missing a few codes to be able to get the output that I wanted. Let me know how to fix this thankyou sm. "Write a function that displays the given number with the corresponding commas in place. The commas are used to divide each period in the number."

CodePudding user response:

Use 1000 as a factor to determine the number of sets of three digits.
Not necessary to count the number of digits.

#include<stdio.h>

int getDivisor ( int nVal) {
    int nDiv = 1;
    while ( nVal < -999 || nVal > 999) { // more than three digits
        nDiv *= 1000;
        nVal /= 1000;
    }
    return nDiv;
}

void displayWithComma ( int nVal) {
    int showsign = 1;
    int nLeftDigits = 0;
    int nMult = getDivisor ( nVal);

    while ( nVal) {
        nLeftDigits = nVal / nMult; // get left digits
        nVal -= nLeftDigits * nMult; // remove left digits from nVal
        if ( showsign) { // show - sign
            printf ( "%d", nLeftDigits);
            showsign = 0;
        }
        else { // do not show - sign
            if ( nLeftDigits < 0) {
                nLeftDigits *= -1;
            }
            printf ( ",d", nLeftDigits);
        }
        nMult /= 1000;
        if ( ! nMult) {
            nMult = 1; // make sure not zero
        }
    }

    printf("\n");
}

int main ( void) {
    displayWithComma ( -23);
    displayWithComma ( 27369);
    displayWithComma ( -1238246);
    displayWithComma ( -1543000698);
    displayWithComma ( 1543000698);
    return 0;
}
  • Related