简体   繁体   English

为什么运算符不给出不同的结果而是使用 = 给出正确的答案

[英]Why is not operator giving different result but using = giving correct answer

 static int count = 0;

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    count = 0;
    int n = sc.nextInt();
    int arr[][] = new int[n][n];
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < n; j++) {
        arr[i][j] = sc.nextInt();
      }
    }
    for (int i = 0; i < n ; i++) {
      row(arr, n, i);
      column(arr, n, i);
    }
    System.out.println(count);
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < n; j++) {
        System.out.print(arr[i][j] + " ");
      }
    }
  }

  static void row(int arr[][], int n, int row) {
    int x, y, min, yHold = 0;

    for (x = 0; x < n; x++) {
      boolean yes = false;
      min = arr[row][x];

      for (y = row; y < n; y++) {
        if (arr[y][x] < min) {
          min = arr[y][x];
          yHold = y;
          yes = true;
        }
      }
      if (yes) {
        int temp = arr[row][x];
        arr[row][x] = min;
        arr[yHold][x] = temp;
        count++;
      }
    }

If I replace yes=true with yes=!yes , the output becomes different.如果我将yes=true替换为yes=!yes ,则 output 会变得不同。 Please help, can't seem to figure it out.请帮助,似乎无法弄清楚。 The part of the problem the function row is taking are of is: function 行的问题部分是:

If we are at ith row, then we have to work with each column at a time from 0 to n−1 of this row.如果我们在第 i 行,那么我们必须从该行的 0 到 n-1 一次处理每一列。 For any jth column, swap A[i][j] with the minimum of all the elements which are present in a column with index j and rows from indices i to n−1.对于任何第 j 列,将 A[i][j] 与索引为 j 的列中存在的所有元素中的最小值以及从索引 i 到 n-1 的行交换。

The problem is that the statement can be executed multiple times.问题是该语句可以执行多次。 In the case of yes = true , the result will always be that yes becomes true .yes = true的情况下,结果将始终是yes变为true But with yes = !yes , the result is that yes will flip flop between true and false .但是使用yes = !yes ,结果是yes将在truefalse之间翻转。

When you say yes = true , it is always going to be true.当您说yes = true时,它总是正确的。 But when you say, yes = !yes it will flip back and forth between true and false.但是当你说yes = !yes时,它会在真假之间来回切换。

boolean yes = true;
for (int i = i < 10; i++) {
 System.out.println(yes);   
 yes =! yes;
}

prints印刷

true
false
true
false
true
false
true
false
true
false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM