信奥一本通:基因相关性求解

自写代码如下:

#include<bits/stdc++.h>
#include <string.h>
using namespace std;
char s[100005]={0};
int main(){
    float stand;

    char a[1024];
    char b[1024];
    int cnt=0,sum=0;
    cin>>stand>>a>>b;
    for(int i=1;i<=strlen(a);i++)
    {
        for(int j=1;j<=strlen(b);j++)
        {
            if(a[i]==b[j])
            {
                cnt++;
            }
        }
        sum++;
    }
    if(1.0*cnt/sum>=stand)
    {
        cout<<"yes";
    }else{
        cout<<"no";
    }
    return 0;
}


答案错了一半,求指教!

以下回答有借鉴GPT

  • 您需要包含头文件 ,而不是 <bits/stdc++.h>。

  • 您可以使用 std::string 类型代替字符数组 char s[100005],这样就不需要使用 strlen 函数。

  • 在 for 循环中,您需要使用 i < strlen(a) 和 j < strlen(b),而不是 i <= strlen(a) 和 j <= strlen(b)。因为字符串的下标是从 0 开始的。

  • 您需要将输入的字符串转换为小写字母,以避免大小写的影响。

下面是修正后的代码:

#include <iostream>
#include <string>

int main() {
    float stand;
    std::string a, b;
    int cnt = 0, sum = 0;

    std::cin >> stand >> a >> b;

    // 将字符串转换为小写字母
    for (auto& c : a) {
        c = std::tolower(c);
    }
    for (auto& c : b) {
        c = std::tolower(c);
    }

    for (std::size_t i = 0; i < a.length(); i++) {
        for (std::size_t j = 0; j < b.length(); j++) {
            if (a[i] == b[j]) {
                cnt++;
            }
        }
        sum++;
    }

    if (1.0 * cnt / sum >= stand) {
        std::cout << "yes";
    } else {
        std::cout << "no";
    }

    return 0;
}