2016-07-06 24 views
-2

此代碼應打印隨機卡類型(但目前它們代表和數字),然後它打印另一種卡類型,但第二種卡類型將是不同的類型。任何人都可以看到爲什麼這段代碼每次都不起作用嗎?

#include <iostream> 
#include <cstdlib> 
#include <ctime> 
using namespace std; 
struct houses { 
    int house_number; 
    string house_name; 
}; 
int main() 
{ 
    srand(time(NULL)); 
    houses house[4]; 
    house[0].house_number = 0; 
    house[1].house_number = 1; 
    house[2].house_number = 2; 
    house[3].house_number = 3; 
    house[0].house_name = "spades"; 
    house[0].house_name = "hearts"; 
    house[0].house_name = "diamonds"; 
    house[0].house_name = "clubs"; 
    int temp, tempo, tempor; 
    temp = house[(rand() % 4)].house_number; 
    cout << temp << "\n"; 
    tempo = house[(rand() % temp)].house_number; 
    tempor = house[(rand() % (4 - temp)) + temp].house_number; 
    int x = (rand() % 2); 
    if (x == 0) { 
     cout << tempo; 
    } 
    else if (x == 1) { 
     cout << tempor; 
    } 
} 

爲了幫助你理解,這部分中的代碼:[(RAND()%溫度)]試圖產生0之間,然後打印在最後數的隨機數的代碼:[(RAND() %(4-temp))+ temp]嘗試獲取最後打印的數字和數組中最大數字之間的隨機數。這意味着我現在有一個數字更小,一個數字更大但不相同。

我現在認識到,通過爲x生成一個0到1之間的隨機數,然後使用x來確定下一個數字是大於還是小於過去的數字,這意味着如果有3個小數字和1個大數字,一個大號碼與下一個打印的號碼有相同的機會,就像所有3個較小的號碼一樣,但是沒關係,我可以再次分類。

+0

請詳細說明,更多的關於_doesn't WORK_部分。 –

+0

1. [using namespace std is bad](http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-in-c-considered-bad-practice)。 2.縮進代碼。 3.也許'house ... name'應該有除0之外的其他索引號 –

+0

你有沒有可以用來運行它的代碼塊? –

回答

2

也許

house[0].house_name = "spades"; 
house[0].house_name = "hearts"; 
house[0].house_name = "diamonds"; 
house[0].house_name = "clubs"; 

應該

house[0].house_name = "spades"; 
house[1].house_name = "hearts"; 
house[2].house_name = "diamonds"; 
house[3].house_name = "clubs"; 
+0

是的,我應該改變,但atm程序只使用house_name –

相關問題