C語言程序設計-筆記5-數據類型和表達式
例6-1 大小寫英文字母轉換。輸入一樣字符,將其中的大寫字母轉換為相應的小寫字母后輸出,小寫字母轉換為相應的大寫字母后輸出,其他字符按原樣輸出。
#include<stdio.h>
int main(void)
{
char ch;
printf("Input characters:");
ch=getchar();
while(ch!='\n')
{
if(ch>='A'&&ch<='Z')
{
ch=ch-'A'+'a';
}
else if(ch>='a'&&ch<='z')
{
ch=ch-'a'+'A';
}
putchar(ch);
ch=getchar();
}
return 0;
}
例6-2 關系表達式的運用。
#include<stdio.h>
int main(void)
{
char ch='w';
int a=2,b=3,c=1,d,x=10;
printf("%d",a>b==c);
printf("%d",d=a>b);
printf("%d",ch>'a'+1);
printf("%d",d=a+b>c);
printf("%d",b-1==a!=c);
printf("%d\n",3<=x<=5);
return 0;
}
例6-3 邏輯表達式運用。
#include<stdio.h>
int main(void)
{
char ch='w';
int a=2,b=0,c=0;
float x=3.0;
printf("%d",a&&b);
printf("%d",a||b&&c);
printf("%d",!a&&b);
printf("%d",a||3+10&&2);
printf("%d",!(x==2));
printf("%d",!x==2);
printf("%d\n",ch||b);
return 0;
}
例6-4 寫出滿足下列條件的C表達式。
1) x為零。
2) x和y不同時為零。
解答:
1) x==0或!x.
2) !(x==0 && y==0)或x!=0||y!=0或x||y。
例6-5 輸入一行字符,統計其中單詞的個數。所謂“單詞”是指連續不含空格的字符串,各單詞之間用空格分隔,空格數可以是多個。
#include<stdio.h>
int main(void)
{
int cnt,word;
char ch;
word=0;
ch=0;
printf("Input characters:");
while((ch=getchar())!='\n')
{
if(ch==' ')
{
word=0;
}
else if(word==0)
{
word=1;
cnt++;
}
}
printf("%d\n",cnt);
return 0;
}
參考資料
C語言程序設計/何欽銘,顏暉主編.---4版.---北京:高等教育出版社,2020.9
