首页 > 解决方案 > 我的代码似乎不能完美运行(总是相同的消息)

问题描述

大家好,我得到了这个代码,我想检查它是否是完美的数组

perfect array means that the sum of his cases of one line equal the sum of the first case of each line

我试图用数字填充数组,然后将它的总和与它的实际总和进行比较,真正遇到的问题是无论我输入什么,它都显示它是一个完美的数组,即使它不是。请帮助我被困在这里。

#include<stdio.h>

#define l 10
#define c 15
int main() {
  int T[l][c];
  int i, j, som, sl, sc, n;
  bool prl, prc; //parfait ligne ..
  
  // Saisie des données de tb matrice 
  printf("Dimension de la matrice carree (max.50) : ");
  scanf("%d", & n);
  
  //triatemnt de tb matrice
  for (i = 0; i < n; i++)
    for (j = 0; j < n; j++) {
      printf("Element[%d][%d] : ", j, j);
      scanf("%d", & T[i][j]);
    }
    
  // traitement de matrise parfait
  som = 0;
  for (j = 0; j < c; j++) {
    som += T[1][j];
  }
  
  i = 2;
  prl = true;
  while (i <= n && prl) {
    som = 0;
    for (j = 0; j < l; j++) {
      som += T[i][j];
    }
    if (som != sl) {
      prl = false;
    }
    i += 1;
  }
  
  j = 2;
  prc = true;
  while (j <= c && prc) {
    som = 0;
    for (i = 0; i < c; i++) {
      som += T[i][j];
    }
    if (som != sc) {
      prc = false;
    }
    j += 1;
  }
  
  // affiche si parfait ou non 
  if (prl || prc) {
    printf("matrice parfaite \n");
  } else
    printf("matrice non parfaite \n");
    
  // Affichage de la tb matrice 
  printf("Matrice donnee :\n");
  for (i = 0; i < n; i++) {
    for (j = 0; j < n; j++)
      printf("%7d", T[i][j]);
    printf("\n");
  }
  return 0;
}

标签: c

解决方案


好吧,基本上在检查您的代码之后,您似乎已将这两个值初始化为 0

int sl=0,sc=0;

其次,当我打印它们时,我注意到它们得到随机值(自己尝试)

 printf("SL = %d , SC = %d",sl,sc);

所以我建议你重新检查你的算法,因为你的整个代码没有包含它们有任何价值,但你仍然将它们与你的总和进行比较。

if (som!=sc) {
      prc=false;
             }

也在这里

  if (som!=sl) {
      prl=false;
             }

I'm not aware of your perfect array, but i guess sc and sl should be included in a for loop and add them some sum of what you wanted to compare them to

also i have noticed that you always open the brackets . it's not wrong , but it's not always correct as you need to take a note that if your action includes one statement (action) simply write it directly exemple from your code :

 for (i = 0; i < c; i++) {
  som += T[i][j];
}

can be direcly to

 for (i = 0; i < c; i++)
  som += T[i][j];

推荐阅读