1. Linux编译 C ,打印 hello world
- 安装 gcc
# yum install -y gcc
- 编辑源文件 helloworld.c
# cat helloworld.c
#include <stdio.h>
main()
{
printf("hello world!!\n");
}
- 将 helloworld.c 的C程序编译为名叫 helloworld 的可执行文件
# gcc -o helloworld helloworld.c
- 执行生成的可执行文件
# ./helloworld
- 实现如下
2. 编写代码实现求10!
#include<stdio.h>
main()
{
int i=2,n=10;
float fac=1;
if(n==0||n==1)
{
printf("factorial is 1.\n");
return 0;
}
while(i<=n)
{
fac=fac*i;
i++;
}
printf("factorial of %d is:%.2f\n",n,fac);
}
3.三个数由小到大排序
#include<stdio.h>
main()
{
int a,b,c,t;
printf("Please input a,b,c:\n");
scanf("%d%d%d",&a,&b,&c);
if(a>b)
{
t = a;
a = b;
b = t;
}
if(a>c)
{
t = a;
a = c;
c = t;
}
if(b>c)
{
t = b;
b = c;
c = t;
}
printf("The order of the number is:\n");
printf("%d,%d,%d\n",a,b,c);
}
4.猴子吃桃问题
小猴子第一天摘下若干个桃子,当即吃了一半,还不过瘾,又多吃了一个。第二天早上又将第一天剩下的桃子吃掉一半,又多吃了一个。以后每天在上都吃了前一天剩下的一半零一个。到第10天早上想再吃时,发现只剩下一个桃子了。编写程序求猴子第一天共摘了多少个桃子。
#include<stdio.h>
main()
{
int day,x1,x2;
day=9;
x2=1;
while(day>0)
{
x1=(x2+1)*2;
x2=x1;
day--;
}
printf("the total is %d\n",x1);
}
5.阳阳买苹果
阳阳买苹果,每个苹果0.8元,阳阳第一天买两个苹果,第二天开始每天买前一天的两倍,直到购买的苹果个数为不超过100的最大值,编程求阳阳每天平均花多少钱?
#include<stdio.h>
main()
{
int n=2,day=0;
float money=0,ave;
while(n<100)
{
money+=0.8*n;
day++;
n*=2;
}
ave=money/day;
printf("The result is %.6f\n",ave);
}