【问题标题】:Strictly Identical arrays input严格相同的数组输入
【发布时间】:2017-04-19 11:25:21
【问题描述】:

清理此代码的任何一般提示? 看来我可以在不进行所有检查的情况下完成任务..

谢谢!

txt书问题: (严格相同的数组)如果两个数组 list1[] 和 list2[] 具有相同的长度并且每个 [i] 的 list1[] 等于 list2[],则它们是严格相同的。

如果list1和list2严格相同,则使用以下标头编写一个返回true的函数

  bool strictlyEqual(const int list1[], const int list2[], int size)

编写一个测试程序,提示用户输入两个整数列表并显示两者是否严格相同。示例运行如下。请注意,输入中的第一个数字表示列表中元素的数量。此号码不在列表中。假设列表大小是最大的

我的代码:

   #include <iostream>
   using namespace std;

   bool strictlyEqual(int const list1[], int const list2[], int size);

   bool strictlyEqual (int x1[], int x2[], int n)
   {
     int f=0; int i;
     for (i =1; i<=n; i++)
     {
               if (x1[i] != x2[])
               {
                  // breaks loop
                    f=1;
                    break;
                }
     } 

 if (f==0)
 return (true);
 else 
 return(false);
 }


int main ()
cout << "enter list1: " << endl;
int list1[20], i;
cin >> list1[0];
for (i=1; i<= list1[0]; i++)
cin>> list1[i];

cout <<"enter the list2" << endl;
int list2[20];
cin >> list2[0];
for (i=1; i<= list2[0]; i++)
cin >> list2[i];

if (list1[0] == list2[0]
{
     int size = list2[0];
     bool v=strictlyEqual(list1, list2, size);
     if (v== true)
     cout << "identical" << endl;
     else 
     cout << "not identical " << endl;
 }

  return 0;
 }

【问题讨论】:

  • 你应该在数组元素5 5 4 3 2 1之间添加空格。
  • @HiI'mFrogatto 谢谢!清理此代码的任何一般提示?只是看起来有点乱..
  • 我还是不明白你的问题是什么?错误?
  • @HiI'mFrogatto 没有错误。您对空间的建议似乎起到了作用。只是要求任何一般提示来清理此代码?看来我可以在不做所有检查的情况下完成任务。谢谢
  • 如果您有工作代码需要反馈,您应该在Code Review 上发帖。

标签: c++ arrays boolean


【解决方案1】:

一个简单的解决方案是使用memcmp 函数。

int memcmp ( const void * ptr1, const void * ptr2, size_t num );

ptr1指向的内存块的第一个num字节与ptr2指向的第一个num字节进行比较,如果它们都匹配则返回零,或者与零不同的值表示如果他们没有。

bool strictlyEqual (int x1[], int x2[], int n){
    return memcmp(x1, x2, n * sizeof(int)) == 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-29
    • 1970-01-01
    相关资源
    最近更新 更多