2017-01-27 109 views
-1

我在我的数组中存储了四个数字,00,11,22,33。当我生成一个随机数并打印它时,它显示0而不是00(当选择第一个元素时)。其他数字很好,并正确显示。如何将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); 
} 
+0

Umm,00等于0.所以程序显示正确。 –

+3

不要喜欢格式化和缩进。只缩进嵌套。并阅读整数和字符串/字符序列之间的区别。 – Olaf

回答

2

00的数量,是完全一样0数量,同时11显然是从1不同数量。

请考虑存储字符串。另外,如果你想使用%02d为您的格式化字符串显示00,仅有2个字符:

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

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

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

%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的完整列表。

相关问题