注册 登录
编程论坛 C语言论坛

得不到正确结果,求大佬赐教

opq2020 发布于 2020-04-29 16:08, 2098 次点击
如有 char str[100],输入一个字符串统计其中数字、大写字母、小写字母和其他字
符的个数,并将大写字母转换为小写字母,小写字母转换为大写字母
#include<stdio.h>
int main()
{char str[100],a[100],b[100];int i=0,k=0,p=0,l=0,c=0;
gets(str);
while(str[i]!='\0')
{
if(str[i]>='0'&&str[i]<='9')
k++;
else if(str[i]>='A'&&str[i]<='Z')
p++,a[i]=str[i]+32;
 else if(str[i]>='a'&&str[i]<='z')
l++,b[i]=str[i]-32;
else c++;i++;
}puts(a);puts(b);  
printf("数字的个数%d 大写字母个数是%d 小写字母个数是%d 其他字符个数是%d",k,p,l,c);}
只有本站会员才能查看附件,请 登录

5 回复
#2
纯蓝之刃2020-04-29 16:17
程序代码:
#include<stdio.h>
int main()
{
    char str[100]={0},a[100]={0},b[100]={0};    //这里
    int i=0,k=0,p=0,l=0,c=0;
    gets(str);
    while(str[i]!='\0')
    {
        if(str[i]>='0'&&str[i]<='9')
            k++;
        else if(str[i]>='A'&&str[i]<='Z')
            a[p++]=str[i]+32;               //这里
        else if(str[i]>='a'&&str[i]<='z')
            b[l++]=str[i]-32;               //这里
        else
            c++;
        i++;
    }
    puts(a);
    puts(b);
    printf("数字的个数%d 大写字母个数是%d 小写字母个数是%d 其他字符个数是%d",k,p,l,c);
}
#3
opq20202020-04-29 20:27
谢谢大佬

#4
forever742020-04-29 21:06
不合题意的程序恐怕仅有苦劳。
题目显然是要你原地转换大小写,没有让你把字母都集中起来呀。
#5
qing_yx2020-04-30 13:07
#include <stdio.h>

int main()
{
    char str[100] = { 0 };
    int num_upper = 0, num_lower = 0, num_number = 0, num_other = 0;
    int i = 0;

    printf("请输入一串字符:");
    gets(str);

    while (str[i] != '\0')
    {
        if (str[i] >= 'a' && str[i] <= 'z')
        {
            num_lower++;
            str[i] -= 32;
        }            
        else if (str[i] >= 'A' && str[i] <= 'Z')
        {
            num_upper++;
            str[i] += 32;
        }
        else if (str[i] >= '0' && str[i] <= '9')
            num_number++;
        else num_other++;

        i++;
    }
    puts(str);
    printf("大写字母=%d,小写字母=%d,数字=%d,其他=%d", num_upper, num_lower, num_number, num_other);

    getchar();
    return 0;
}

输出正确

[此贴子已经被作者于2020-5-6 10:58编辑过]

#6
qing_yx2020-04-30 13:22
回复 4楼 forever74
#include <stdio.h>

int main()
{
    char str[100] = { 0 };
    int num_upper = 0, num_lower = 0, num_number = 0, num_other = 0;
    int i = 0;

    printf("请输入一串字符:");
    gets(str);

    while (str[i++] != '\0')
    {
        if (str[i] >= 'a' && str[i] <= 'z')
        {
            num_lower++;
            str[i] -= 32;
        }            
        else if (str[i] >= 'A' && str[i] <= 'Z')
        {
            num_upper++;
            str[i] += 32;
        }
        else if (str[i] >= '0' && str[i] <= '9')
            num_number++;
        else num_other++;
    }
    puts(str);
    printf("大写字母=%d,小写字母=%d,数字=%d,其他=%d", num_upper, num_lower, num_number, num_other);

    getchar();
    return 0;
}
如果我从键盘输入I love U!!123 转换后为什么输出I LOVE u!!123,统计数字第一个I算其他字符,不算大写字母,这是为什么?
如果I love U!!123 最前面加个其他什么字符,统计就是对的。
只要第一个字符是字母,无论大小写,都算作其他字符。。。。
1