while语句和do..while语句课后习题

while语句和do…while语句

  1. 统计从键盘输入的一行英文句子中大写字母的个数。
    答:代码如下:
#include <stdio.h>

int main()
{
    char ch;
    int count = 0;
    while((ch=getchar())!='\n')
    {
        if(ch >= 'A' && ch <= 'Z')
            count++;       
    }
    printf("total = %d\n",count);

    return 0;
}

运行结果如下:

dym@ubuntu:~/project/c_proj/FishC/test$ gcc test.c -o test && ./test
Hello I am DYM!
total = 5
  1. C 语言中有个 atoi 函数(定义于 <stdlib.h> 头文件中),用于将字符串中的值解析为对应的整型数字。现在要求我们自己写一个程序,实现类似的功能。
    基本要求:
    A. 将用户输入的字符串中代表数字的字符转换为整型数值
    B. 打印转换结果
    C. 只打印第一组数字
    提示:你可以使用 break 语句在适当的时候跳出循环。
    答:代码如下
#include <stdio.h>

int main()
{
    char ch;
    int count = 0;
    printf("please input a string:");
    while((ch=getchar())!='\n')
    {
        if(ch >= '0' && ch <= '9')
        {
            printf("%d",ch - 48);
            count++;
        }
        else
        {
            if(count)
            {
                printf("\n");
                break;
            }
        }
    }

    return 0;
}

运算结果如下:

dym@ubuntu:~/project/c_proj/FishC/test$ gcc test.c -o test && ./test
please input a string:0as.1
0
  1. 写一个程序,将用户输入的英文句子中的字母大小写进行调换(即大写字母转换为小写字母,小写字母转换为大写字母)。
    提示:你可能会需要使用 putchar 函数。
    答:代码如下:
#include <stdio.h>

int main()
{
    char ch;
    printf("please input a string:");
    while((ch=getchar())!='\n')
    {
        if(ch >= 'a' && ch <= 'z')
        {
            ch = ch&0xDF;
            putchar(ch);
        }
        else if(ch >='A' && ch <='Z')
        {
            ch = ch|0x20;
            putchar(ch);
        }
        else
            putchar(ch);        
    }
    printf("\n");
    return 0;
}

改进版:

#include <stdio.h>

int main()
{
    char ch;
    printf("please input a string:");
    while((ch = getchar()) != '\n')
    {
        ch = ch ^ 0x20;
        putchar(ch);
    }
    putchar('\n');
    return 0;
}

运行结果如下:

dym@ubuntu:~/project/c_proj/FishC/test$ gcc test.c -o test && ./test
please input a string:HeLlo!
hElLO!
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值