【问题标题】:Check how many items added in c array? [closed]检查c数组中添加了多少项? [关闭]
【发布时间】:2016-08-31 13:20:23
【问题描述】:

我已经声明了一个长度为 100 的 c 数组。现在,我将 char 放入其中:

char northl2[100];

northl2[0]='1';
northl2[1]='1';

如何计算我的程序放入数组中的 1 的数量?

【问题讨论】:

标签: c dev-c++


【解决方案1】:

你可以使用这样的循环:

char northl2[100] = {0};

northl2[0]='1';
northl2[1]='1';
int count_one = 0;
for (int i = 0;i<100;++i)
{
    if (northl2[i] == '1')
    {
        ++count_one;
    }
}
std::cout << count_one;

在这种情况下打印 2,因为有 2 个1。代码遍历数组的每个元素,检查它的值,并增加它的计数。 char northl2[100] = {0}; 默认将每个元素设置为 0。如果您需要不同的值,请使用循环:

char northl2[100];
int main()
{
    int count_one = 0;
    for (int i = 0; i< 100;++i)
    {
         northl2[i] = 'C'; //Or whatever char other than '1'
    }
    northl2[0]='1';
    northl2[1]='1';
    for (int i = 0;i<100;++i)
    {
        if (northl2[i] == '1')
        {
            ++count_one;
        }
    }
}

另外,不要忘记在循环为所有元素赋值后分配 1,否则,它们将被覆盖

【讨论】:

  • 但是在我的 prog 中做得很好的数组是全局的
  • 你可以使用循环,我会编辑我的答案
  • @MurshadGill 答案已编辑
  • 干得好,这已经完成了,谢谢你知道最后任何人都可以分享一个链接,如何在c 中使用线程执行函数
  • 呃,如果您发现它是正确的,您能否通过单击答案左侧的绿色复选标记图标将其中一个答案标记为正确,以便其他人可以得到这个答案的帮助?另外,您的问题还不清楚@MurshadGill
【解决方案2】:

您可以使用默认值初始化数组,例如0:

char northl2[100] = { 0 };

然后在您添加之后,您的 '1' 字符会循环执行,并为您找到的每个 '1' 增加一个计数器变量。

【讨论】:

    【解决方案3】:

    在没有标记值的数组中保留实际元素数量的唯一方法是定义一个变量来存储数组中实际值的数量。

    考虑到如果这个声明

    char northl2[100];
    

    是块范围声明,则数组未初始化并且具有不确定的值。

    如果您将值作为字符串存储在字符数组中(即该数组具有标记值 '\0'),那么您只需应用标准 C 函数 std::strlen

    您可以通过以下方式定义数组

    char northl2[100] = {};
    

    最初将数组的所有元素初始化为零。

    在这种情况下你可以写

    char northl2[100] = {};
    
    northl2[0] = '1';
    northl2[1] = '1';
    
    //...
    
    std::cout << "The number of added values to the array is " 
              << std::strlen( northl2 )
              << std::endl;
    

    假设值是按顺序添加的,数组中没有间隙。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-07
      相关资源
      最近更新 更多