算法学习之C语言基础

算法学习,先熟悉一下C语言哈!!!

#include <conio.h>
#include<stdio.h>
int main(){
    printf("%d
",1+2);
    getch();
    return 0;
}

计算1+2的值
结果:3



进一步计算加减乘除

#include <conio.h>
#include<stdio.h>
int main(){
    printf("%d
",1+2);
    printf("%d
",3-4);
    printf("%d
",5*6);
    printf("%d
",8/4);
    printf("%d
",8/5);
    getch();
    return 0;
}

结果:
3
-1
30
2
1
tips:计算发现8除以5得到的不是1.6而是1,为什么呢?
如果才能得到1.6呢?


#include <conio.h>
#include<stdio.h>
int main(){
    printf("%.1lf
",8.0/5.0);//第二个是字母l
    getch();
    return 0;
}

结果:
1.6


进一步实验

#include <conio.h>
#include<stdio.h>
int main(){
    printf("%.2lf
",8.0/5.0);//2表示小数点后的尾数保留
    printf("%.1lf
",8.0/5.0);//1表示只保留一位
    printf("%.lf
",8.0/5.0);//没有则表示保留0位,四舍五入
    printf("%.1lf
",8/5);//不明
    printf("%d
",8.0/5.0);//不明
    getch();
    return 0;
}

结果:
1.60
1.6
2
1.6
-1717986918
tips:整数用%d输出,实数用%lf输出,整数与整数运算结果也是整数对于整数运算。
8.0和5.0称为实数,更专业一点叫“浮点数”。浮点数之间的运算也是浮点数。
额,我表示还是有点晕乎乎的!!!
再来看一看更复杂一点的算术表达式。

#include <conio.h>
#include<stdio.h>
#include<math.h>
int main(){
    printf("%.8lf
",1+2*sqrt(4)/(1-0.75));//sqrt必须引入math.h头文件
    getch();
    return 0;
}

结果:17.00000000
tips:整数-浮点数=浮点数
确切的说是整数先变成浮点数,然后浮点数-浮点数=浮点数

变量及其输入
下面是可以处理输入两个数的代码

#include <conio.h>
#include<stdio.h>
int main(){
    int a,b;
    scanf("%d%d",&a,&b);
    printf("%d
",a+b);
    getch();
    return 0;
}



tips:scanf中的占位符合变量的数据类型一一对应,且每个变量前需要&符号。

计算圆柱体的表面积
要求:输入底面半径r和高h,输出圆柱体的表面积,保留3位小数。
样例输入:3.5 9
样例输出:Area = 274.889
分析:圆柱体表面积由3部分组成:上底面积、下底面积和侧面积。
完成的公式可写成:表面积=底面积*2+侧面积

#include <conio.h>
#include<stdio.h>
#include<math.h>
int main(){
    const double pi = 4.0*atan(1.0); //pi的巧妙获取
    double r,h,s1,s2,s; //声明变量
    scanf("%lf%lf",&r,&h); //获取输入值
    s1 = pi*r*r; //计算底面积
    s2 = 2*pi*r*h; //计算侧面积
    s = s1*2.0 + s2; //得到总面积
    printf("Area = %.3lf
",s); //输出结果
    getch();
    return 0;
}



 

原文地址:https://www.cnblogs.com/jiqing9006/p/3185063.html