【问题标题】:Comparing two arrays in C?比较C中的两个数组?
【发布时间】:2014-11-07 05:05:57
【问题描述】:

所以我有两个数组,a[17] 和 b[12]。我想比较每个数字的前 12 个数字,如果数字匹配,则打印出“0”,如果不匹配,则打印出“1”。但它不起作用。它应该打印“000001111111”但它没有。谁能告诉我为什么?

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>

int main(){

int i, j;

int a[17] = {1,0,1,0,0,1,0,1,0,1,0,0,0,1,1,0,1};
int b[12] = {1,0,1,0,0,0,1,0,1,0,1,1}; 

for(i=0;i<12;i++)
for(j=0;j<12;j++)
   if(a[i] == b[j])
      printf("1");
   else
      printf("0");


system("pause");
return 0;
}

【问题讨论】:

  • * 抱歉,如果相应的数字匹配,则应打印 0。例如,如果 a[1] 和 b[1] 匹配,则应打印 0。
  • 如果他们有帮助并解决了问题,请不要忘记 应用 答案。 (您的个人资料中有 3 个问题尚未应用)

标签: c arrays algorithm


【解决方案1】:

你的代码应该是:

for(i=0;i<12;i++) {
   if(a[i] == b[i]) {
      printf("1");
   } else {
      printf("0");
   }
}

不需要两个循环。

您想比较具有相同索引的数组中的元素,因此两个数组的索引i 应该相同。

【讨论】:

  • @EdHeal 谢谢。我会的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多