while語句和do..while語句課後習題
阿新 • • 發佈:2021-01-16
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;
}
執行結果如下:
[email protected]:~/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;
}
運算結果如下:
[email protected]:~/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;
}
執行結果如下:
[email protected]:~/project/c_proj/FishC/test$ gcc test.c -o test && ./test
please input a string:HeLlo!
hElLO!