首页 > 代码库 > 选择结构的程序设计和循环结构的程序设计
选择结构的程序设计和循环结构的程序设计
if语句
eg:
#include<stdio.h>
int main(void){
int age;
scanf("%d",&age);
if(age>18){
printf("您已经是成年人了!");
}
}
if -else语句
eg:
#include<stdio.h>
int main(void){
int age;
scanf("%d",&age);
if(age>18){
printf("您已经是成年人了!");
}
else{
printf("您还是个未成年人!");
}
}
switch语句
eg:
#include<stdio.h>
int main(void){
int y,m,d,y1,m1,d1;
int td,td1,xg,yxg,td2;
printf("请输入第一个正确的年月日:");
scanf("%d %d %d",&y,&m,&d);
printf("请输入第二个正确的年月日:");
scanf("%d %d %d",&y1,&m1,&d1);
if(y==y1){
switch(m){
case 1:td=d;break;
case 2:td=31+d;break;
case 3:td=59+d;break;
case 4:td=90+d;break;
case 5:td=120+d;break;
case 6:td=151+d;break;
case 7:td=181+d;break;
case 8:td=212+d;break;
case 9:td=243+d;break;
case 10:td=273+d;break;
case 11:td=304+d;break;
case 12:td=334+d;break;
}
switch(m1){
case 1:td1=d1;break;
case 2:td1=31+d1;break;
case 3:td1=59+d1;break;
case 4:td1=90+d1;break;
case 5:td1=120+d1;break;
case 6:td1=151+d1;break;
case 7:td1=181+d1;break;
case 8:td1=212+d1;break;
case 9:td1=243+d1;break;
case 10:td1=273+d1;break;
case 11:td1=304+d1;break;
case 12:td1=334+d1;break;
}
if(y%4==0&&y%100!=0||y%400==0){
if(m>2){
td++;
if (m1>2){
td1++;
}
}
}
xg=td1-td;
}else{
switch(m){
case 1:td=d;break;
case 2:td=31+d;break;
case 3:td=59+d;break;
case 4:td=90+d;break;
case 5:td=120+d;break;
case 6:td=151+d;break;
case 7:td=181+d;break;
case 8:td=212+d;break;
case 9:td=243+d;break;
case 10:td=273+d;break;
case 11:td=304+d;break;
case 12:td=334+d;break;
}
if(y%4==0&&y%100!=0||y%400==0){
td2=366-td;
}else{
td2=365-td;
}
switch(m1){
case 1:td1=d1;break;
case 2:td1=31+d1;break;
case 3:td1=59+d1;break;
case 4:td1=90+d1;break;
case 5:td1=120+d1;break;
case 6:td1=151+d1;break;
case 7:td1=181+d1;break;
case 8:td1=212+d1;break;
case 9:td1=243+d1;break;
case 10:td1=273+d1;break;
case 11:td1=304+d1;break;
case 12:td1=334+d1;break;
}
yxg=(y1-y)-1;
xg=365*yxg+td2+td1;
for(yxg=y+1;yxg<y1;yxg++){
if(yxg%4==0&&yxg%100!=0||yxg%400==0){
xg++;
}
}
}
printf("两个年份之间相隔%d天\n",xg);
}
while语句
eg:
#include<stdio.h>
int main(void){
int s,i;
s=0;
i=1;
while(i<=100){
s+=i;
i++;
}
printf("1+2+3+4……+100=%d\n",s);
}
do-while语句
eg:
#include<stdio.h>
int main(void){
int i,n;
long s;
s=1;
i=1;
printf("请输入n:\n");
scanf("%d",&n);
do{
s*=i;
i++;
}
while(i<=n);
printf("%d!=%ld\n",n,s);
}
for语句
eg:
#include <stdio.h>
int main(void){
int taozi=1;
int i;
for( i=9;i>=1;i--){
taozi=(taozi+1)*2;
}
printf("桃子数量为%d",taozi);
}