while语句和do…while语句
- 统计从键盘输入的一行英文句子中大写字母的个数。
答:代码如下:
#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
- 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
- 写一个程序,将用户输入的英文句子中的字母大小写进行调换(即大写字母转换为小写字母,小写字母转换为大写字母)。
提示:你可能会需要使用 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!