Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
124 views
in Technique[技术] by (71.8m points)

c++ - How to check if in arrays column all numbers are negative?

I created an array of A[rows][columns] random numbers between 100 and -100 saved it in txt file Now i have to check if all numbers are negative in column and if so save column number in array C[x];

    int main()
{
    ofstream out("masyvas.txt");
    srand(time(0));
    int n=rand() % (31 - 10) + 10; // eilutes
    int m=rand() % (31 - 10) + 10; // stulepliai

    int A[n][m];

  for(int i=0; i<n; i++)
    for(int j=0; j<m; j++)
            A[i][j]=rand()%100 + (rand()%100 *(-1)) ;
 for(int i=0; i<n; i++)
  {
      for(int j=0; j<m; j++)
            out<<setw(5)<<A[i][j]<<" ";
      out<<endl;
  }
  out.close();
 //------------------------------------------
    return 0;
}

so above everything is ok but

     ofstream rez("rez.txt");
 for(int i=0; i < m;i++)
 {
     for(int j=0; j< n;j++) {
        if(A[i][j]<0){
                rez << i <<" - column" << j << "- row"<< endl;
        }
     }
 }
    cout << n << endl << m << endl;
    rez.close();

first i wanted to print into txt file if it finds negative numbers correctly but i get some nonsense and i have no clue what to do im stuck for half an hour trying to do different things

question from:https://stackoverflow.com/questions/65853166/how-to-check-if-in-arrays-column-all-numbers-are-negative

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First thing, don't panic, read your code and actually know what it is doing.

To check if all numbers in a column are negative, you need to loop over an entire column first while having something, preferably a boolean, to tell you if any of them is not negative.

For example: create a flag that defaults to true.

bool allNegative = true;
for ( int i =0; i < (sizeof(matrix[0])/sizeof(int)); i++)
{
  if(matrix[i][0] > 0) allNegative = false; // change the flag to indicate that it is not all negative
}

Then what you want to do is if the flag is still true, loop that column again to just copy and paste all this code for each row to output that column to a txt file.

out<<setw(5)<<A[i][j]<<" ";
out<<endl;

EDIT: thanks to comment, I have changed the syntax error.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...