【问题标题】:regarding scope of variable in C关于C中变量的范围
【发布时间】:2013-12-04 19:09:39
【问题描述】:
#include<stdio.h>
int countdigits(int n);
int main(void)
{
   int t,k;
   scanf("%d %d",&t,&k);

   long long N[t];
   int i;

   for (i=0;i<t;i++)
   {

       scanf("%lld",&N[i]);
   }

int j,main_count=0;
for (j=0;j<t;j++)
{

    int counter=0;
    while (N[j] !=0)
    {

        if (N[j]%10 <=k)
        {
            counter++;
        }
        else
            ;
        N[j]=N[j]/10;
    }
        if (counter==countdigits(N[j]))
            main_count+=1;

}
   printf("%d",main_count);

    return 0;
}

int countdigits(int n)
{
    int num,counter=0;
    num=n;
    for(;num !=0;num=num/10)
    {
        counter++;
    }

    return counter;
}

我对算法很确定,问题就在这里
如果一个数字包含不超过 k (0, ..., k) 的所有数字,我们就称它为 k-good。
您有一个数字 k 和一个包含 n 个数字的数组 a。
找出 a 中有多少个 k-good 数(每次出现在数组 a 中时计算每个数)。

输入
第一行包含整数 n 和 k (1 ≤ n ≤ 100, 0 ≤ k ≤ 9)。以下 n 行中的第 i 行包含不带前导零的整数 ai (1 ≤ ai ≤ 109)。

输出
打印一个整数——a 中的 k-good 数。

谁能告诉我哪里出错了?

【问题讨论】:

  • 你担心哪个变量的作用域?
  • 第二个样本输出是 1 怎么样?!
  • 为什么要将所有数字读入一个数组? (您可以像那样动态分配数组吗?也许我已经过时了)为什么不只是在读取它们时处理它们?
  • if (counter==countdigits(N[j])) ?! N[j] 在这里为零!!因为 N[j]=N[j]/10;而条件

标签: c scope


【解决方案1】:
#include<iostream>
#include<string>
using namespace std;

int main()
{
  string s;
  int n, k, count = 0;
  cin >> n >> k;
  while (n--)
  {
      cin >> s;
      int f[10] = {0};
      bool good = true;
      for (int i=0;i<s.size();i++)
          f[s[i]-'0']=1;

      for (int i=0;i<=k;i++)
          if (f[i]==0)
             good = false;
      if (good)
          count ++;
  }
  cout << count << endl;
  return 0;
}

现场接受的代码。诀窍在于“包含所有不超过的数字”。问题描述说所有数字 k。大于 k 的数字存在或不存在这一事实并不重要。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-14
    • 2011-12-23
    • 2012-04-09
    • 1970-01-01
    相关资源
    最近更新 更多