lsmCC 发表于 2023-10-24 22:32:49

找出不同的个数

#include <bits/stdc++.h>
using namespace std;
const int N =1010;
int a,b;
int main()
{
    int n,cnt=0;
    cin>>n;
    memset(b,0,sizeof(b));
    for(int i=0;i<n;i++)cin>>a;
    for(int j=0;j<n;j++)
    {
      b]++;
    }
    for(int j=0;j<n;j++)
    {
      if(b]==0)cnt++;
    }
   cout<<cnt<<endl;
}
修改代码,为什么cnt=0呢
输入
5
1 1 2 4 5

isdkz 发表于 2023-10-24 22:33:07

在给定的代码中,cnt被用作计数器,用于记录出现次数为0的不同元素的个数。初始时将cnt设置为0是因为我们还没有遍历数组a,因此还没有找到任何出现次数为0的元素。

在代码中,首先通过cin读取整数n,表示数组a的长度。然后使用memset将数组b的所有元素初始化为0。

接下来,使用for循环遍历数组a,并使用b]++语句将数组b中对应元素的计数器加1。这样,数组b中的每个元素都表示了对应的数字在数组a中出现的次数。

然后,再次使用for循环遍历数组a,并通过判断b]是否为0来确定是否为不同的元素。如果b]为0,说明该元素在数组a中出现的次数为0,即为不同的元素,将cnt加1。

最后,输出cnt的值,即出现次数为0的不同元素的个数。

对于给定的输入5 1 1 2 4 5,程序的执行过程如下:
· 首先读取整数n,得到n=5。
· 然后将数组b的所有元素初始化为0。
· 接下来,使用for循环遍历数组a,将数组b中对应元素的计数器加1。此时,数组b的元素分别为0 2 1 0 1,表示数字1出现了2次,数字2出现了1次,数字3没有出现,数字4出现了1次,数字5出现了1次。
· 再次使用for循环遍历数组a,判断b]是否为0。对于给定的输入,数组a的元素分别为1 1 2 4 5。第一个元素1在数组b中的计数器为2,不为0,因此不是不同的元素。第二个元素1在数组b中的计数器也为2,不为0,同样不是不同的元素。第三个元素2在数组b中的计数器为1,不为0,也不是不同的元素。第四个元素4在数组b中的计数器为1,不为0,同样不是不同的元素。最后一个元素5在数组b中的计数器为1,不为0,同样不是不同的元素。
· 最后,输出cnt的值为0,表示没有出现次数为0的不同元素。

因此,对于给定的输入,程序输出的结果是0。

陶远航 发表于 2023-10-24 22:33:08

The variable cnt is initialized to 0 (cnt = 0) at the beginning of the code because it is used to count the number of distinct elements. By setting it to 0 initially, we ensure that it starts counting from zero before iterating through the array.

Regarding the input you provided (5 1 1 2 4 5), there seems to be an error as the first number "5" does not represent the number of elements in the array. It appears to be part of the array itself. If you provide the correct input format, I can assist you with modifying the code accordingly.
请注意,本回答来自GPT-4
如果问题已经解决,请设置最佳答案
页: [1]
查看完整版本: 找出不同的个数