你能发现这段代码中的逻辑错误吗?计数

标签 c

我编写的程序有问题。我无法获得输入字符串的正确字数,但我获得了正确的最长字符数。我不知道为什么,但这是我的代码。我正在做的是将一个字符串传递给一个函数,该函数将字符串中的所有字母大写。然后,该函数逐个确定字符是否在 A-Z 范围内,如果在 A-Z 范围内,则将最长的连续字符 A-Z 计数(称为 charcount)加一。然后从那里应该查找前一个字符是否不在 A-Z 范围内。如果不是,则计算新单词。最后的数组将计数传递给主函数。忽略所有额外的字符串。这里的重点是我的字数统计有问题,我找不到它。

#include <stdio.h>
void convert(char s[], int counts[]);

int main(void)
{
     int i = 0;
     int aray[2];
     char text0[] = "This is one of Several strings2use.";
     char text1[] = "This sample has less than 987654321 leTTers.";
     char text2[] = "Is thIs a string?  (definitely)";
     char text3[] = "Twitter loves its hashtags #twitterlove";
     char text4[] = "123 four five.";
     convert(text3,aray);
     printf("wordcount is %d and longest char is %d ", aray[0],aray[1]);




}

void convert(char s[], int counts[])
{
     int i = 0;

     while(s[i] != '\0')
     {
         if('a' <= s[i] && s[i] <= 'z')
          {   s[i] = s[i] - 32; }
         i = i + 1;
     }
     int h = 0;
     int wordcount = 0;
     int maxcount = 0;
     int charcount = 0;
     while(s[h] != '\0')
     {
         if('A'<= s[h]&& s[h] <= 'Z')
         {    
             charcount = charcount + 1;
             if ('A' >= s[h-1] && s[h-1] >= 'Z'); """if previous not in range"""
             {
                 wordcount = wordcount + 1;} """problem here"""
         }
         else
             charcount = 0;
         if(charcount>maxcount)
             {
             maxcount = charcount;
             }
        h = h+1;         

     }
         counts[0] = wordcount;
         counts[1] = maxcount;


}

最佳答案

在这一行中:

if ('A' >= s[h-1] && s[h-1] >= 'Z');

...if 语句的主体是“;”。它后面的 block 只是一个普通 block 并且将始终执行。您需要删除分号。

关于你能发现这段代码中的逻辑错误吗?计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21705776/

相关文章:

卷积结果与caffe不同

c - nasm 中的链接 c 函数

c - 如何将数组包含到 C 函数定义中

c++ - 如何使用 ODBC 处理长字符串?

c - 让 GCC 在没有内联汇编的情况下使用进位逻辑进行任意精度运算?

C boolean 无效值处理

c - 如何使用c找到DFS中的组件数量?

c - 段错误,无法递增

C编程-3 if语句中的测试条件

C 中的凯撒密码有时只有效?