How do I fill in the first zero and print it out?

Asked 1 years ago, Updated 1 years ago, 76 views

Like the zip code, we're going to print an integer that matches 5 to 6 digits Is there an easier way than the code I made?

/*
num : Integer to output, 
len : Number of digits
*/
void printWith0(int num, int len){
    int num0 = len-num/10;
    int i;
    for (i=1; i<num0; i++) {
        printf("0");
    }
    printf("%d", num);
}


int main() {
    int mynum = 1;
    printWith0(mynum, 5);
}

c printf

2022-09-21 16:14

1 Answers

c has a format specifier that supports this feature. Attach 0 immediately after the specifier % followed by a digit, then add a format specifier that fits the type

However, in the case of floating points, it means to fill in 0 to n decimal places, not integer parts, so please write the two separately.

Example:

int main() {
    printf("%05d\n", 303);
    printf("%010d\n", 303);
    printf("%05f\n", 3.03);
}

Output:

00303
0000000303
3.030000


2022-09-21 16:14

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.