OJ题目练习:
文章目录
1. 获得月份天数
输入年份和月份,计算这一年这个月有多少天。
1.1 switch语句
#include <stdio.h>
int main()
{
int y=0;
int m=0;
while(scanf("%d%d",&y,&m)==2)
{
switch(m)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
printf("%d\n",31);
break;
case 4:
case 6:
case 9:
case 11:
printf("%d\n",30);
break;
case 2:
{
if(((y%4==0)&&(y%100!=0)||(y%400==0)))
printf("%d\n",29);
else
printf("%d\n",28);
}
}
}
return 0;
}
1.2 调用一个函数
int is_leap_year(int y)
{
return (((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0));
}
int main()
{
int y = 0;
int m = 0;
int days[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
//用0为了下标与天数对位
while (scanf("%d%d", &y, &m) == 2)
{
int day = days[m];
if (is_leap_year(y) && m == 2)
{
day++;
}
printf("%d\n", day);
}
return 0;
}
2. 判断是不是字母
判断输入的字符是不是字母。
2.1 应用getchar
int main()
{
int ch = 0;
while ((ch = getchar()) != EOF)
//getchar在缓冲区拿取数据,处理缓冲区的\n
{
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
printf("%c is an alphabet.\n", ch);
else
printf("%c is not an alphabet.\n", ch);
getchar();
//处理缓冲区中多余的\n
}
return 0;
}
2.2 应用scanf
2.2.1 用 getchar();
int main()
{
int ch = 0;
while (scanf("%c",&ch)==1)
{
if ((ch >= 'a' && ch <= 'z') ||(ch >= 'A' && ch <= 'Z'))
printf("%c is an alphabet.\n", ch);
else
printf("%c is not an alphabet.\n", ch);
getchar();
}
return 0;
}
2.2.2 不用 getchar()(少用)
int main()
{
int ch = 0;
while (scanf("%c\n",&ch)== 1)
{
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
printf("%c is an alphabet.\n", ch);
else
printf("%c is not an alphabet.\n", ch);
}
return 0;
}
2.3 采用库函数 isalpha
3. 字母大小写转换
有一个字符,判断它是否为大写字母,如果是,将它转换成小写字母;反之则转换为大写字母。
3.1 应用getchar()
//A - 65
//a - 97,差32
int main()
{
int ch = 0;
while ((ch = getchar()) != EOF)
{
if (ch >= 'A' && ch <= 'Z')
{
printf("%c\n", ch + 32);//小写了
}
else if (ch >= 'a' && ch <= 'z')
{
printf("%c\n", ch - 32);
}
//处理\n
getchar();
}
return 0;
}
3.2 应用库函数
#include<ctype.h>
int main()
{
int ch = 0;
while ((ch = getchar()) != EOF)
{
if (isupper(ch))
{
printf("%c\n", tolower(ch));//小写了
}
else if (islower(ch))
{
printf("%c\n", toupper(ch));
}
//处理\n
getchar();
}
return 0;
}
4. 网购
#include<stdio.h>
int main()
{
double price = 0.0;
int m = 0;
int d = 0;
int flag = 0;
scanf("%lf %d %d %d", &price, &m, &d, &flag);
if (m == 11 && d == 11)
price = price * 0.7 - flag * 50;
else if (m == 12 && d == 12)
price = price * 0.8 - flag * 50;
if (price < 0.0)
price = 0.0;
printf("%.2lf\n", price);
return 0;
}