1.快递费用计算(详细整理版)
题目要求如下:
思路:
运用switch语句嵌套if语句实现,先分区,再分重。
分重量时,超重部分不足一公斤的按一公斤收费,则可以通过向上取整的数学函数实现,此处我用ceil。ceil可以计算不小于它的最小整数值,不用担心遇到整数会取下一整数的问题。
ceil示例:
#include <stdio.h>
#include <math.h>
int main(void)
{
printf("ceil(+2.4) = %+.lf\n", ceil(2.4));//ceil(+2.4) = +3.0
printf("ceil(-2.4) = %+.lf\n", ceil(-2.4));//ceil(-2.4) = -2.0
}
那么运用到本题中,则可以:
#include <stdio.h>
int main()
{
double i=3.3;
printf("%d",(int)ceil(i));
return 0;
}
注:ceil学习资料来自https://zh.cppreference.com/w/c/header
代码实现如下:
#include <stdio.h>
#include <math.h>
int main(void)
{
int i = 0;
double g, Price = 0;
scanf("%d,%lf", &i, &g);
switch (i)
{
default:
Price = 0;
printf("Error in Area\nPrice: %.2lf", Price);
break;
case 0:
{
if (g <= 1)
{
Price = 10;
}
else if (g > 1)
{
Price = 10 + (int)ceil(g - 1) * 3;
}
break;
}
case 1:
{
if (g <= 1)
{
Price = 10;
}
else if (g > 1)
{
Price = 10 + (int)ceil(g - 1) * 4;
}
break;
}
case 2:
{
if (g <= 1)
{
Price = 15;
}
else if (g > 1)
{
Price = 15 + (int)ceil(g - 1) * 5;
}
break;
}
case 3:
{
if (g <= 1)
{
Price = 15;
}
else if (g > 1)
{
Price = 15 + (int)ceil(g - 1) * 6.5;
}
break;
}
case 4:
{
if (g <= 1)
{
Price = 15;
}
else if (g > 1)
{
Price = 15 + (int)ceil(g - 1) * 10;
}
break;
}
}
if (Price!= 0)
{
printf("Price: %.2lf", Price);
}
return 0;
}
其中switch语句注意在case后适当加上break,continue等指令使程序正常进行。
2.字符串中各类字符数的统计
题目要求:
输入一行字符,分别统计出其中英文字母、数字、空格和其他字符的个数。
思路:
首先需要输入一串未知长度字符串,可以使用fgets()函数,它比gets()函数安全,会限制读取的字符数量,防止缓冲区溢出。
fgets示例:
#include <stdio.h>
int main()
{
char str[100];
fgets(str,100,stdin);
printf("%s",str);
return 0;
}
需要注意的是:该函数会读取换行符,如图:
要移除换行符,可以进行如下操作:
注意要包含头文件<string.h>
代码实现如下:
#include <stdio.h>
int main() {
char str[1000];
fgets(str, 1000, stdin);
int letters = 0;
int digits = 0;
int spaces = 0;
int others = 0;
int i = 0;
while (str[i] != '\0')
{
if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z'))
{
letters++;
}
else if (str[i] >= '0' && str[i] <= '9')
{
digits++;
}
else if (str[i] == ' ')
{
spaces++;
}
else
{
others++;
}
i++;
}
printf("%d ", letters);
printf("%d ", digits);
printf("%d ", spaces);
printf("%d", others-1);
return 0;
}