【问题标题】:How to store 00 in an array?如何将00存储在数组中?
【发布时间】:2017-01-27 19:51:11
【问题描述】:

我在数组00,11,22,33 中存储了四个数字。当我生成一个随机数并打印它时,它显示0 而不是00 (选择第一个元素时)。其他数字都很好并且显示正确。如何将 00 存储在数组中以便正确显示?

#include <stdio.h>
#include <stdlib.h>
#include <time.h>  

int main()
{
    srand(time(NULL));
    int myArray[4] = { 00,11,22,33 };
    int randomIndex = rand() % 4;
    int randomIndex1 = rand() % 4;
    int randomIndex2 = rand() % 4;
    int randomIndex3 = rand() % 4;

    int randomValue = myArray[randomIndex];
    int randomValue1 = myArray[randomIndex1];
    int randomValue2 = myArray[randomIndex2];
    int randomValue3 = myArray[randomIndex3];
    printf("= %d\n", randomValue);
    printf("= %d\n", randomValue1);
    printf("= %d\n", randomValue2);
    printf("= %d\n", randomValue3); 

    return(0);
}

【问题讨论】:

  • 嗯,00等于0。所以程序显示正确。
  • 不要对格式和缩进花哨。缩进只嵌套。并了解整数和字符串/字符序列之间的区别。

标签: c printf srand


【解决方案1】:

00这个数字,和0这个数字完全一样,而11显然和1是一个不同的数字。

考虑改为存储字符串。或者,如果您想显示00,只需使用%02d 作为格式化字符串的两个字符:

printf("= %02d\n", randomValue);

如果这真的是你的整个程序,你甚至可以只修改你的数组,然后打印两次值:

int myArray[4] = {0,1,2,3};
. . .
printf("= %d%d\n", randomValue, randomValue);

【讨论】:

    【解决方案2】:

    %02d 扫描码将打印带有零填充的随机数:

    printf("%02d\n", randomValue);
    // Expected output for 0: 00
                              ^
                         This 0 belongs to the scan code 
    

    另外,%2d 扫描码会为你做空格填充:

    printf("%2d\n", randomValue);
    // Expected output for 0:  0
                              ^
                         This space belongs to the scan code
    

    一般%(0)NM是一个扫描码,其中:

    • 0 是可选的,它属于数字,如果使用它,它将在输出中添加零填充;如果不使用,则会添加空格填充。

    • N 是您要打印的数字/字符数,例如2

    • M 是您想要显示数据类型的扫描码,例如{d, x, c, s, ...}代表{number, hexadecimal number, character, string, ...}

    您可以找到扫描码here的完整列表。

    【讨论】:

      猜你喜欢
      • 2022-06-10
      • 1970-01-01
      • 1970-01-01
      • 2014-08-18
      • 1970-01-01
      • 1970-01-01
      • 2015-07-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多