2017-01-27 108 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的完整列表。

相關問題