Contents of this article
-
- 1. Calculate the average salary of company employees. The number of people in the unit is not fixed, and the salary number is entered from the keyboard. When -1 is entered, the input is completed (the previous input is valid data)
- 2. Enter a year randomly on the keyboard to determine whether it is a leap year.
- 3. While loop finds the sum of the first n items
- 4. Find the sum of the first n items in a do while loop
- 5. The for loop finds the sum of the first n items
- 6. Find the sum of the factorials of the first n terms
1. Calculate the average salary of company employees. The number of people in the unit is not fixed, and the salary number is entered from the keyboard. When -1 is entered, the input is completed (the previous input is valid data)
// 平均工资代码
#include <stdio.h>
int main()
{
int n=0;
float wage=0,sum=0,average_wage;
printf("please input the wage of staff\n(每输入一个工资后空格输入下一个工资,输入-1结束输入):\n");
while(wage!=-1)
{
scanf("%f",&wage);
if(wage==-1)
break;
sum=sum+wage;
n++;
}
average_wage=sum/n;
printf("The average wage is %0.2f.\n",average_wage);
return 0;
}
2. Enter a year randomly on the keyboard to determine whether it is a leap year.
// 闰年判断代码
#include <stdio.h>
int main()
{
int year,leap;
printf("please input a year: ");
scanf("%d",&year);
if((year%4==0&&year%100!=0||year%400==0))
{
printf("%d是闰年",year);
}
else
{
printf("%d不是闰年\n",year);
}
return 0;
3. While loop finds the sum of the first n items
// while循环求前n项和
#include <stdio.h>
int main()
{
int i,sum=0;
i=1;
while(i<=99)
{
sum=sum+i;
i++;
}
printf("%d\n",sum);
return 0;
}
4. Find the sum of the first n items in a do while loop
// do while循环求前n项和
#include <stdio.h>
int main()
{
int i,sum=0;
i=1;
do
{
sum=sum+i;
i++;
}
while(i<=100);
printf("%d\n",sum);
return 0;
}
5. The for loop finds the sum of the first n items
// for 循环求n项和
#include <stdio.h>
int main()
{
int i,sum=0;
i=1;
for(i=1;i<=100;i++)
{
sum=sum+i;
}
printf("%d\n",sum);
return 0;
}
6. Find the sum of the factorials of the first n terms
// 求前n项阶乘之和
#include <stdio.h>
int main()
{
int i,sum=0,a=1;
i=1;
for(i=1;i<=20;i++)
{
a=i*a; //阶乘表达式
sum=sum+a; //求和
}
printf("%d\n",sum);
return 0;
}
The above codes have been debugged and can be used with confidence.