2014-02-28 36 views
-4

你可以幫助我一個不同的程序。 ..它引入了一個範圍的數字(無限制,你可以重複數字),其中顯示每個數字輸入的次數.. 例如:1 3 4 3 3 6 1 結果: 1-2x 3- 3x 4-1x 6-1x範圍的數字和顯示數字重複C++

謝謝不錯。

#include <iostream> 
#include <cstdlib> 
using namespace std; 
int rnd() 
{ 
    int iRand = (rand() % 100) + 1; 
} 

int hundred_random() 
{ 
    for (int rCount=0; rCount < 100; ++rCount) 
    { 
     cout << rnd() << endl; 
    } 
} 

int main() 
{ 
    cout << " The list of Hundred random numbers are- " << endl; 
    hundred_random(); 
    return 0; 
} 
+3

你需要什麼幫助?到目前爲止您嘗試過哪些具體的問題? – BoBTFish

+6

我們不應該爲你編寫程序。告訴我們你已經嘗試過了。如果您遇到任何問題,我們很樂意爲您提供幫助。 –

+1

看看[std :: map](http://en.cppreference.com/w/cpp/container/map)。或者如果你使用C++ 11,[std :: unordered_map](http://en.cppreference.com/w/cpp/container/unordered_map)。如果您有任何代碼示例,請將其編輯到您的問題中,因爲您無法在註釋中格式化代碼。 –

回答

1

爲了怎麼算經常在號碼列表中出現的每個號碼,您可以執行以下操作:

#include <iostream> 
#include <vector> 
#include <map> 
#include <cstdlib> 

我們需要這些頭輸出,存儲的號碼,存儲計,和rand()來生成示例。

std::vector<int> generate_numbers(int amount, int max_num) 
{ 
    std::vector<int> numbers(amount); 
    for (int i = 0; i < amount; ++i) { 
     numbers[i] = rand() % max_num + 1; 
    } 
    return numbers; 
} 

生成一串隨機數的幫助方法。

std::map<int, int> count_numbers(const std::vector<int> &numbers) 
{ 
    // Count numbers 
    std::map<int, int> counts; // We will store the count in a map for fast lookup (C++11's unordered_map has even faster lookup) 
    for (size_t i = 0; i < numbers.size(); ++i) { // For each number 
     counts[numbers[i]]++; // Add 1 to its count 
    } 
    return counts; 
} 

上面的方法計算,這是你的問題的本質。對於我們遇到的每個數字,我們增加它的計數。

void print_counts(const std::map<int, int> &counts) 
{ 
    for(std::map<int, int>::const_iterator it = counts.begin(); 
     it != counts.end(); ++it) { // For each number stored in the map (this automatically filters those with count 0) 
     std::cout << it->first << ": " << it->second << std::endl; // Output its count 
    } 
} 

最後,顯示我們的結果的方法。由於我們從未對任何出現零次的數字採取行動,因此它們不在地圖中,並且將從輸出中省略。

int main() { 
    srand(0); // So that we get the same result every time 
    std::vector<int> numbers = generate_numbers(10000, 500); 
    std::map<int, int> counts = count_numbers(numbers); 
    return 0; 
} 

把它放在一起。 See this code run