2013-04-18 51 views
3

我想爲溫度生成一個隨機數。我使用的代碼是下面:C++不正確顯示隨機數

int Temp() 
{ 
    // genreate random temperture 

    // initialize random seed: 
    srand (time (NULL)); 

    // generate number between 1 and 100: 
    int t = rand() % 100 + 1; 

    std::cout << t << std::endl; 
    return t; 
} 

當該程序在執行的,而不是顯示在1和100之間的數,它顯示以下內容:

010C1109 

有人能解釋其中或爲什麼它是出錯了?

編輯:如果有人想知道我用了以下內容:

#include <iostream> 
#include <string> 
#include <fstream> 
#include <istream> 
#include <ctime> 
#include <stdio.h>  
#include <stdlib.h>  
#include <time.h>  
#include <map> 
#include <cstdlib> 
#include <cstring> 
#pragma once 
+4

也許你面前經過'的std :: hex'到'的std :: cout'。 – deepmax

+0

忘了提及我正在調用這個函數。只是出於某種原因,它不能正確顯示。 我沒有使用std :: hex,我從來沒有用過它 – user1582575

+0

你能重現嗎?每次你運行這個代碼,你會得到這樣的結果? – fen

回答

2

如何選擇顯示你的號碼的方式:我看到 58進制和88

std::cout << std::hex << t << std::endl; //displays in hexadecimal 
std::cout << std::dec << t << std::endl; //displays in decimal 

在我的例子十進制(5 * 16 + 8)。 以下是完成發佈的官方鏈接。

C++論壇:

http://www.cplusplus.com/forum/windows/51591/

詳細解釋:

http://www.cplusplus.com/reference/ios/dec/

+0

OP給出的例子是十六進制的,但它比'int t = rand()%100 + 1'可能產生的要大得多('0x010C1109' =='17568009'),除非還有其他意想不到的事情發生。看起來更像是一個內存地址給我。 – jerry

+0

另外,有人[在評論中已經問過'std :: hex'](http://stackoverflow.com/questions/16084349/c-not-displaying-random-number-correctly#comment22961563_16084349)。 [OP不使用它](http://stackoverflow.com/questions/16084349/c-not-displaying-random-number-correctly#comment22961671_16084349)。 – jerry