【问题标题】:a problem in comparing two arrays' elements比较两个数组元素的问题
【发布时间】:2021-08-20 02:36:07
【问题描述】:

作为萨拉姆·阿莱科姆。 在这段代码中,我试图打印特定段落的每个字母字符的重复次数,如下所示:

a ----> "Number of recurrences"
b ----> "Number of recurrences"
and so on...

通过使用 stricmp 函数在每个循环中比较两个数组的元素。但它根本不打印任何东西和0个错误,这是什么问题?!?!?!?!?

#inlcude <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <math.h>
#include <string.h>
#include <time.h>

void main()
{
    int i, j;
    int z = 0;
    char h, g;
    char y[26] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
    char x[620] = {"C is a general purpose computer programming language developed in 1972 by Dennis Ritchie at the Bell Telephone laboratories for use with the unix operating system... and more which is not visible in the image."}; 
    for(j = 0; j < 26; j++)
    {
        for(i = 0; i < 609; i++)
        {
            if(stricmp(y[j], x[i]) == 0)
            {
                z++;
            }
        }
        printf("y[j] -------> %d", z);
    }

}

【问题讨论】:

  • 请勿发布代码图片。将代码本身以文本形式复制并粘贴到问题中。
  • stricmp 需要字符串,而不是 chars。启用您的编译器警告。
  • 在每个内部for循环启动后z的值为零。

标签: arrays c string


【解决方案1】:

这里的问题是你在比较characters没有strings

在 C 中,字符串是字符数组,末尾带有 '\0'。

例如:

这是一个 C 字符:'C'

这是一个 C 字符串:'C\0'

stricmp 需要两个字符串,而您要传递两个字符。

所以要实现解决方案你需要比较字符和你的程序正在运行。

if(toupper(y[j]) == toupper(x[i]))

#include <stdlib.h>
#include <conio.h>
#include <math.h>
#include <string.h>
#include <time.h>

void main()
{
    int i, j;
    int z = 0;
    char h, g;
    char y[26] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
    char x[620] = {"C is a general purpose computer programming language developed in 1972 by Dennis Ritchie at the Bell Telephone laboratories for use with the unix operating system... and more which is not visible in the image."}; 
    for(j = 0; j < 26; j++)
    {
        for(i = 0; i < 609; i++)
        {

            if(toupper(y[j]) == toupper(x[i]))
            {
                z++;
            }
        }
        printf("y[j] -------> %d \n", z);
    }

}

【讨论】:

    猜你喜欢
    • 2016-06-19
    • 1970-01-01
    • 2021-05-06
    • 2017-08-29
    • 1970-01-01
    • 2021-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多