题目1
编写程序,实现下列格式的乘法口诀表
1*1=1
2*1=2 2*2=4
3*1=3 3*2=6 3*3=9
4*1=4 4*2=8 4*3=12 4*4=16
5*1=5 5*2=10 5*3=15 5*4=20 5*5=25
6*1=6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36
7*1=7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49
8*1=8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64
9*1=9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81
解题思路
- 从第一行开始,输出该行上每一列的结果,直到当行等于列时(包含该列)
- 循环输出每一行
流程图
源代码
#include <stdio.h>
#define N 9
void printTable();
int main()
{
printTable();
return 0;
}
void printTable()
{
for(int i=1; i<=N; i++)
{
for(int j=1; j<=i; j++)
{
printf("%d*%d=%d\t", i,j, i*j);
}
printf("\n");
}
}
题目2
从键盘输入100个人的姓名、性别和年龄,分别统计0-29岁、30-59岁、60以上的男、女人数
解题思路
- 定义people结构体类型,包含姓名、性别和年龄
- 输入100个人的信息
- 统计各个年龄段的男性和女性的人数
- 输出结果
流程图
源代码
#include <stdio.h>
#include <string.h>
#define N 100
struct people{
char name[20];
char sex[3];
int age;
};
void input(struct people pe[]);
void count(struct people pe[], int age_0_29[], int age_30_59[], int age_60[]);
int main()
{
struct people pe[N];
int age_0_29[2] = {0}, age_30_59[2] = {0}, age_60[2] = {0}; //第一个元素是女性人数,第二个元素是男性人数
input(pe);
count(pe, age_0_29, age_30_59, age_60);
printf("0-29岁女性人数: %d\t, 男性人数: %d\n", age_0_29[0], age_0_29[1]);
printf("30-59岁女性人数: %d\t, 男性人数: %d\n", age_30_59[0], age_30_59[1]);
printf("60岁以上女性人数: %d\t, 男性人数: %d\n", age_60[0], age_60[1]);
return 0;
}
void input(struct people pe[])
{
for(int i=0; i<N; i++)
{
printf("请输入第%d个人的姓名: ", i+1);
scanf("%s", pe[i].name);
getchar();
printf("请输入第%d个人的性别(男或女): ", i+1);
scanf("%s", &pe[i].sex);
getchar();
printf("请输入第%d个人的年龄: ", i+1);
scanf("%d", &pe[i].age);
}
}
void count(struct people pe[], int age_0_29[], int age_30_59[], int age_60[])
{
for(int i=0; i<N; i++)
{
if(pe[i].age>=0 && pe[i].age<=29)
{
if(strcmp(pe[i].sex,"女")==0)
{
age_0_29[0]++;
}
if(strcmp(pe[i].sex,"男")==0)
{
age_0_29[1]++;
}
}
if(pe[i].age>=30 && pe[i].age<=59)
{
if(strcmp(pe[i].sex,"女")==0)
{
age_30_59[0]++;
}
if(strcmp(pe[i].sex,"男")==0)
{
age_30_59[1]++;
}
}
if(pe[i].age>=60)
{
if(strcmp(pe[i].sex,"女")==0)
{
age_60[0]++;
}
if(strcmp(pe[i].sex,"男")==0)
{
age_60[1]++;
}
}
}
}
小结
该题有两个地方需要注意
- 性别的存储问题。如果用中文表示,则一个中文占两个char类型。这时应当用字符数组存储,而不是单个的字符变量。同样在进行性别判断的时候,也要用字符串的处理函数。另外可以用数字来表示性别,比如:0表示女性,1表示男性
- 在输入每个人的信息的时候,各个信息输入之间应当用getchar消化掉回车,不然就会吧回车读入到下一个信息段中。
题目3
从键盘上输入字符串1,将字符串I中除去数字字符’0’ ~ ‘9’之后的其它字符保留在字符串2中,开输出字符串2
解题思路
- 定义两个字符数组用于存放字符串1和字符串2
- 从键盘输入字符串1
- 逐个将字符串1中除了‘0’~‘9’的字符放到字符串2 中
- 输出字符串2
流程图
源代码
#include <stdio.h>
#include <string.h>
#define N 255
void inputA(char str1[]);
void reform(char str1[], char str2[]);
int main()
{
char str1[N], str2[N]={'\0'};
inputA(str1);
reform(str1, str2);
printf("str2:%s", str2);
return 0;
}
void inputA(char str1[])
{
printf("请输入一个字符串: ");
scanf("%s", str1);
}
void reform(char str1[], char str2[])
{
int i=0, j=0;
while(str1[i] != '\0')
{
if(str1[i]>='0' && str1[i]<='9')
{
i++;
}else
{
str2[j] = str1[i];
j++;
i++;
}
}
}