【问题标题】:find method giving wrong answer in c++在 C++ 中找到给出错误答案的方法
【发布时间】:2019-06-17 11:54:57
【问题描述】:

在下面的代码中,我们必须首先计算字符串中存在的统一子字符串的权重。统一子字符串是那些只包含一个字符的字符串,例如“a”或“aaa”。字符的权重定义为a-1 b-2......z-26。

在计算所有有效统一子字符串的权重后,我们将收到各种查询,我们必须检查给定的 no.是不是数组。

这里是代码的链接和对应的输出: https://www.ideone.com/pIBPtQ

#include<bits/stdc++.h>
using namespace std;

int main()
{
  string s;
  cin>>s;
  int i=0,j=0,k=0;
  int arr[10000];
  int c=0;  
  while(s[i]!='\0')
  {
    int x=(int)s[i];
    x=x-96;
    arr[c++]=x;
    j=i+1;
    int sum=x;
    while(s[j]==s[i])
    {
      sum+=x;
      arr[c++]=sum;
      j++;
    }
    i=j;
  }
  int q;
  cin>>q;
  for(i=0;i<q;i++)
  {
    int val;
    cin>>val;
    bool exists=find(begin(arr),end(arr),val)!=end(arr);
    if(exists==true)
      cout<<"Yes"<<endl;
    else
      cout<<"No"<<endl;
  }
  cout<<"the elements of the array are:"<<endl;
  for(i=0;i<c;i++)
    cout<<arr[i]<<" ";
  return 0;
}

【问题讨论】:

  • 不要以链接的形式提供样本输入和实际+期望的输出。将它们发布在您的问题中。
  • 供将来参考:从不 #include&lt;bits/stdc++.h&gt;。使用公共标头,而不是内部实现细节。

标签: c++ arrays string find c++14


【解决方案1】:

你忘了初始化arr

改变

int arr[1000];

int arr[1000] = {0};

https://www.ideone.com/wIj4vp

另外x=x-96;最好写成x -= 'a';

【讨论】:

  • 回复:“写得更好”——是的,但它仍然是错误的。 并非所有世界都是 ASCII。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-19
相关资源
最近更新 更多