一、顺序结构
程序举例:
1、财务人员给员工发工资时经常遇到这样一个问题,即根据每个人的工资额(以元作为单位)计算出各种面值的钞票的张数,且要求总张数最少。
例如,某职工工资为3436元,发放方案为:100元34张,20元1张,10元1张,5元1张,1元1张。
#include
int main()
{
int money;
scanf("%d",&money);
int m100;
int m50;
int m20;
int m10;
int m5;
m100 = money / 100;
money %= 100;
m50 = money / 50;
money %= 50;
m20 = money / 20;
money %= 20;
m10 = money / 10;
money %= 10;
m5 = money / 5;
money %= 5;
printf("m100 = %d,m50 = %d,m20 = %d,m10 = %d,m5 = %d,m1 = %d\n",
m100,m50,m20,m10,m5,money);
return 0;
}
2、从键盘输入一个大写字母,要求改用小写字母输出。
#include
int main()
{
char ch;
printf("please input ch = ");
scanf("%c",&ch);
if((ch >= 'A') && (ch <= 'Z'))
{
char ch_change = ch + 'a' - 'A';
printf("%c\n",ch_change);
}
else
{
printf("input is error\n");
}
return 0;
}
二、选择结构
程序举例:
1、判某一年是否闰年。输入:年(year)计算:判是否闰年输出:闰年或非闰年(leap)闰年条件:能被4整除,但不能被100整除。能被4整除,又能被400整除。
#include
int main()
{
int year;
scanf("%d",&year);
int flag = 0;
if(0 == year % 4)
{
if(0 == year % 100)
{
if(0 == year % 400)
{
flag = 1;
}
}
else
{
flag = 1;
}
}
if(1 == flag)
{
printf("this year = %d is leap\n",year);
}
else
{
printf("this year = %d is not leap\n",year);
}
return 0;
}
2、编写一个能进行两个操作数加减乘除四则运算的计数器模拟程序输入:两个操作数和运算符计算:根据运算符确定运算;输出:运算结果。
#include
int main()
{
char op;
float a,b;
scanf("%f%c%f",&a,&op,&b);
switch(op)
{
case '+':
printf("=%5.2f\n",a+b);
break;
case '-':
printf("=%5.2f\n",a-b);
break;
case '*':
printf("=%5.2f\n",a*b);
break;
case '/':
if(0 == b)
{
printf("b = 0\n");
}
else
{
printf("=%5.2f\n",a/b);
}
default:
printf("op is error\n");
}
return 0;
}
三、循环结构
程序举例:
1、计算一条语句中的空格、字母、数字的个数。
#include
int main()
{
int letter_count = 0;
int space_count = 0;
int num_count = 0;
char ch;
while(ch != '\n')
{
scanf("%c",&ch);
if((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'))
{
letter_count++;
}
if(ch == ' ')
{
space_count++;
}
if(ch >= '0' && ch <= '9')
{
num_count++;
}
}
printf("letter_count = %d,space_count = %d,num_count = %d\n",
letter_count,space_count,num_count);
return 0;
}
2、判断数字m是否为素数(质数)。
#include
int main()
{
int num;
scanf("%d",&num);
int i;
int count = 0;
for(i = 2;i < num;i++)
{
if(0 == num % i)
{
count++;
}
}
if(0 == count)
{
printf("True : %d\n",num);
}
else
{
printf("False : %d\n",num);
}
return 0;
}
3、题目:通过编程实现,统计0~n有多少个9 。提示:n通过参数传入
#include
int main()
{
int i;
int n;
int count = 0;
int temp;
scanf("%d",&n);
for(i = 0;i <= n;i++)
{
temp = i;
while(0 != temp)
{
if(9 == temp % 10)
{
count++;
}
temp /= 10;
}
}
printf("count = %d\n",count);
return 0;
}