2017-08-17 106 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