顺序,选择,循环。C语言的十八般武艺,大多在于这三件神器的排列组合。
而作为for的忠实拥趸,while和do-while在康妮猫的电脑上实现了半永久退休。
到了这章终于和数学思维扯上点儿关系了,请看编程题:
1.计算购货款
代码如下:
<span style="font-size:18px;">#include <stdio.h>
#include <stdlib.h>
int main()
{
float price;
printf("Please input the price:");
scanf("%f",&price);
//该题适合用if-else if做,switch不方便设置开关变量
if(price<=500)
price=price;//原价
else if(price>500&&price<=1000)
price=0.9*price;//九折
else price=0.8*price;//八折
printf("The price after discount is:%.2f",price);//保留两位输出
system("pause");
return 0;
}
</span>
2.直角三角形判定
代码如下:(这里写得比较笨是因为还未到“函数”一节)
<span style="font-size:18px;">#include <stdio.h>
#include <stdlib.h>
int main()
{
float a,b,c,t;
//float a=3,b=4,c=5,t;可预赋值调试
printf("Please input the length of edge a,b,c:\n");
scanf("%f%f%f",&a,&b,&c);
if(a>b)
{
t=a;
a=b;
b=t;
}//将a,b中较大者排到右边
if(b>c)
{
t=b;
b=c;
c=t;
}//将b,c中较大者排到右边,这样保证最右边为最长边(可能的斜边)
if(a*a+b*b==c*c)
printf("Yes,they can: )");
else
printf("Sorry,they can't.");
system("pause");
return 0;
}
</span>
3.数列求和
代码如下:
<span style="font-size:18px;">#include <stdio.h>
#include <stdlib.h>
int main()
{
float a=2,b=1,c,t,s;
int i;
for(i=0;i<20;i++)
{
c=a/b;//单项值
t=a;
a=a+b;
b=t;
//分子母变换
//printf("%f\n",c);用于检查单项值
s+=c;
}
printf("The sum is:%f",s);
system("pause");
return 0;
}
</span>
4.求e的值
4-1
代码如下:
<span style="font-size:18px;">#include <stdio.h>
#include <stdlib.h>
int main()
{
float a=1,b,e;
int i=3,j=2;
for(;i<=20;i++,j++)
{
a*=j;//分母
// printf("a=%f\n",a);检验生成中间项
b=1.0/a;//单项
e+=b;//累项
}
e+=2;//补上前两项
printf("e=%f",e);
system("pause");
return 0;
}
</span>
4-2
代码如下:
<span style="font-size:18px;">#include <stdio.h>
#include <stdlib.h>
int main()
{
float a=1,b=1,e;
int i=2;
while(b>=0.0001)//直至最后一项值小于10^(-4)
{
a*=i;//分母
//printf("a=%f\n",a);用于检验生成中间项
b=1.0/a;//单项
e+=b;//累项
i++;
}
e+=2;//补上前两项
printf("e=%f",e);
system("pause");
return 0;
}
</span>
今日吐槽:俩月前入手的《第一行代码》在诱惑我,我该午睡么?: )