2017-08-17 97 views
-3

這裏是下面的代碼:)我也評論了一些部分,以便更容易理解代碼的輸出。如何計算表中總數-1和總數1? (C++)

我有一個小小的想法,我需要使用「if語句」和「rand()%」來確保程序知道我們只想計算1s和-1s的總和。例如使用「rand()%2-1」可以幫助獲得表中輸出的1的總和。再次,我不確定這個想法是否會起作用。

因此,程序第一次運行時應該輸出類似於「表中的1的數量爲5,表中的-1的數量爲3」的內容。然後當它第二次運行時,它可能會輸出類似於「表格中1的數量爲2並且表格中的數量爲-1s爲5」

對不起,任何混淆和您的所有幫助將高度讚賞:) :)

#include<iostream> 
#include<iomanip> 
#include<ctime> 


using namespace std; 

int main() { 
srand(time(0)); 
const int ROWS=3; 
const int COLS=4; 

int table[ROWS][COLS]; 

for (int i = 0; i < ROWS; i ++) { 
    for (int j = 0; j < COLS; j++) { 
     table[i][j] = rand()%3-1; 
    } 
} 

for (int i = 0; i < ROWS; i ++) { 
    for (int j = 0; j < COLS; j++) 
     cout << setw(3) << table[i][j]; 

    cout << endl; 
} 



bool checkTable [ROWS][COLS]; 

for (int i = 0; i < ROWS; i ++) { 
    for (int j = 0; j < COLS; j++) { 
     if (table[i][j] !=0) { 
checkTable[i][j] = true; 
    } 
    else{ 
checkTable[i][j] = false; 
    } 


    //The output in the line below is the final line outputted by the 
    console. This prints out "1" if there is a value in the index within 
    the table provided above (the value is represented by 1 or -1), and 
    prints out "0" if there is no value in the index (represented by 0) 

    cout << " " << checkTable[i][j]; 



    } 
} 

return 0; 
} 
+5

爲什麼'蘭特('?用隨機數來計算表中1的數量是什麼?一旦你填充了它,你就不需要任何'rand()' – user463035818

+0

在這個編碼中使用「rand()」來使得任務更具挑戰性。有一個-1到0的給定範圍(在表格中輸出-1,0和1)。每次程序運行時,這三個數字通過「rand()」以不同的順序輸出。棘手的問題是如何計算每次程序運行時在表格內輸出的1和-1的數量。由於「rand()」函數每次都會有不同的總數。我剛纔編輯了我的問題以澄清它 – Learning2code

+0

請嘗試澄清問題。目前還不清楚爲什麼你認爲你需要'rand()'來進行計數。此外,我沒有找到代碼,你做任何計數。沒有冒犯,但你的代碼似乎與你的任務無關「計數爲1」 – user463035818

回答

1

[...]爲使用例如 「蘭特()%2-1」 可以與獲得的1秒 在表輸出的總和幫助。

我真的不明白你的意思。計數和隨機性不會很好地結合在一起。我的意思是,當然你可以用隨機數填充矩陣,然後然後做一些計數,但rand()不會幫助任何計數。

你需要簡單的東西爲:)

int main() { 
srand(time(0)); 
const int ROWS=3; 
const int COLS=4; 

int table[ROWS][COLS]; 

for (int i = 0; i < ROWS; i ++) { 
    for (int j = 0; j < COLS; j++) { 
     table[i][j] = rand()%3-1; 
    } 
} 

unsigned ones_counter = 0; 

for (int i = 0; i < ROWS; i ++) { 
    for (int j = 0; j < COLS; j++) {    // dont forget the bracket 
     cout << setw(3) << table[i][j]; 
     if (table[i][j] == 1) { ones_counter++;} // <- this is counting 
    } 
    cout << endl; 
} 

std::cout << "number of 1s in the table : " << ones_counter << "\n"; 
.... 
+0

是啊哈我明白他們不......但這是我的導師提供給我的一項任務。謝謝您的幫助 :) – Learning2code