在C语言编程中如何将零填充元素放入数组中?

问题描述 投票:0回答:1

我想把000到999的随机数放入数组中。

for (i = 0; i < 1000; i++)
{
    arr[i] = rand() % 1000;
    printf("%02d ", arr[i]);
}

这只是打印,我想在数组中做零填充的元素.example)arr = [000,001,002,......999]

有什么方法吗?

c generic-programming
1个回答
0
投票
#include <stdio.h>

int main(void) {
    int arr[1000];
    for (int i = 0; i < 1000; i++)
    {
        arr[i] = rand() % 1000;
        printf("%03d ", arr[i]);
    }
    return 0;
}

IDE一个链接

产量

Success #stdin #stdout 0s 4412KB
383 886 777 915 793 335 386 492 649 421 362 027 690 059 763 926 540 426 172 736 211
368 567 429 782 530 862 123 067 135 929 802 022 058 069 167 393 456 011 042 229 373 
421 919 784 537 198 324 315 370 413 526 091 980 956 873 862 170 996 281 305 925 084
327 336 505 846 729 313 857 124 895 582 545 814 367 434 364 043 750 087 808 276 178
788 584 403 651 754 399 932 060 676 368 739 012 226 586 094 539 795 570 434 378 467
601 097 902 317 492 652 756 301 280 286 441 865 689 444 619 440 729 031 117 097 771
481 675 709 927 567 856 497 353 586 965 306 683 219 624 528 871 732 829 503 019 270
368 708 715 340 149 796 723 618 245 846 451 921 555 379 488 764 228 841 350 193 500
034 764 124 914 987 856 743 491 227 365 859 936 432 551 437 228 275 407 474 121 858
395 029 237 235 793 818 428 143 011 928 529 776 404 443 763 613 538 606 840 904 818

0
投票

你可以不填写 int 因为int类型只存储整数,所以考虑下面的例子。

#include <stdio.h>
    int main(){
        int a = 0001;
        printf("%d\n", a);
        return 0;
    }

上述代码的结果是:

1

就是这样. 顺便说一下, 如果你想有零填充的数字, 你应该把它们打印到一个字符数组中,然后使用... ... sprintf 而是 printf请看下面的例子。

#include <stdio.h>
//include other necessary libraries.

int main(){
    char* randomNumbers[1000];
    //while your numbers are at most 4 digit, I will allocate just 4 bytes:
    for(int i = 0; i < 1000; i++){
        randomNumbers[i] = (char*) calloc(4, sizeof(char));
    }

    //here we go to answer your question and make some random numbers which are zero-padding:
    for(int i = 0; i < 1000; i++){
         int a = rand() % 1000;
         sprintf(randomNumbers[i], "%03d", a);
    }
}

这个... randomNumbers 数组是你合适的数组。

© www.soinside.com 2019 - 2024. All rights reserved.