编程小计算汇总(实时更新)

来源:互联网 发布:淘宝售假违规扣48分 编辑:程序博客网 时间:2024/05/18 12:43
1、实现四舍五入运算:
       问题:假如你有一个float型变量a,其值为1.23456,若保留三位小数,也就是得到1.235。
       解决:只需要令:a = (int)(1000.0 * a + 0.5) / 1000.0 ;   
                  如果要保留四位小数,就把1000都换成10000,依次类推。
2、数据排序
1)冒泡法
#include<stdio.h>void main(){int a[10];   //定义一个数组既它的元素为10int i,j,temp;     //定义3个变量printf("输入10个整数:\n\a");for(i=0;i<10;i++)   scanf("%d",&a[i]); //依次输入10个整数for(i=0;i<9;i++)      //进行9轮排序{   for(j=0;j<9-i;j++) //每轮进行9-i次交换   if(a[j]>a[j+1])   {      temp=a[j];      a[j]=a[j+1];   //大的沉底,小的上浮      a[j+1]=temp;   }}printf("排序结果:");for(i=0;i<10;i++)   //依次输出排序结果   printf("%d\t ",a[i]);}
2)使用vector容器,插入排序
#include <iostream>#include <vector>using namespace std;int main(){vector<int> iVtr;vector<int> :: iterator itVtr;for(int i = 0; i<20; i++){cin >> iVtr.insert(%d);//放入vector会自动排序}for (itVtr = iVtr.begin(); itVtr!=iVtr.end(); itVtr++){cout << *itVtr << endl;}return 0;}
0 0
原创粉丝点击