7 .写一程序,判断某年是否为闰年(多种算法)
法一:if的多层嵌套,注意else对应好if,采用锯齿形,关键最后leap真假的判断函数,注意这种思想
#include <stdio.h>
#include<stdlib.h>
main()
{
int year, leap; /*leap为标志变量,leap=0为闰年,leap=1为平年*/
printf("请输入年份:");
scanf_s("%d", &year, 9999);
if (year % 4 == 0)
{
if (year % 100 == 0)
{
if (year % 400 == 0)
leap = 1;
else
leap = 0;
}
else
leap = 1;
}
else
leap =0;
if (leap)
printf("%d是",year); 最关键部分!!
else
printf("%d不是",year);
printf("闰年\n");
system("pause");
}
法二:用一个逻辑表达式包含所有闰年条件。
#include <stdio.h>
#include<stdlib.h>
#include<conio.h>
main()
{
int year, leap; /*leap为标志变量,leap=0为闰年,leap=1为平年*/
printf("请输入年份:");
scanf_s("%d", &year, 9999);
if( (year % 4 == 0 && year % 100 !=0) || (year % 400 == 0))
leap = 1;
else
leap = 0;
if (leap)
printf("%d是", year);
else
printf("%d不是", year);
printf("闰年\n");
system("pause");
}
8 .求1到100项的和。
#include <stdio.h>
#include<stdlib.h>
main()
{
int i = 1, sum = 0;
while (i <= 100)
{
sum = sum + i;
i++;
}
printf("前100项和为%d\n",sum);
system("pause");
}
9 .for语句无限循环。
for(i=1; ;i++)
10 .在全系1000学生中,征集慈善募款当总数达到10万时停止,统计此时捐款的人数,以及平均每人捐款的数目。
#include <stdio.h>
#include<stdlib.h>
#define SUM 100000 /*宏定义全局变量*/
main()
{
float amount, aver, total; /*amount为输入数值,aver为平均数,total临时存放总数*/
int i;
for (i = 1, total = 0; i <= 1000;i++) /*初始化total*/
{
printf("请输入捐款数:");
scanf_s("%f", &amount); /*执行循环输入*/
total = total + amount;
if (total >= SUM)break; /*关键!嵌入if,总数达到100000时用break跳出,注意跳出思想,total达到100000时跳出*/
}
aver = total / i;
printf("总数为%d\n平均捐款数目为%10.2f", i,aver); /*指定输出形式*/
system("pause");
}