zoukankan      html  css  js  c++  java
  • c++常见操作的模板

    1.统计时间

    #include<ctime>
    clock_t startTime = clock();
    code();
    clock_t endTime = clock();
    cout << endl<< "time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " s"<<endl;
    

    2.读取文件

    #include<iostream>
    #include<fstream>
    #include<cstdlib>
    const int SIZE=60; 
    int main()
    {
    	using namespace std;
    	char filename[SIZE]="information.txt";
    	ifstream inFile;
    	inFile.open(filename);
    	if(!inFile.is_open())
    	{
    		cout<<"Could not open the file"<<filename<<endl;
    		cout<<"Program terminating.
    ";
    		exit(EXIT_FAILURE);
    	}
    	double value;                                                                    //1
    	double sum=0.0;
    	int count=0;
     
        inFile>>value;                                                                     //1
        while(inFile.good())
        {
        	++count;
        	sum=sum+value;
        	inFile>>value;
        }
        if(inFile.eof())
        cout<<"end of file reached.
    ";
    	else if(inFile.fail())
    	cout<<"input terminated by data mismatch.
    ";
    	else
    	cout<<"input terminated for unknown reason.
    ";
    	if(count==0)
    	cout<<"NO DATA PROCESSED.
    ";
    	else{
    		cout<<"items read:"<<count<<endl;
    		cout<<"sum:"<<sum<<endl;
    	}
    	inFile.close();       
         return 0;
    }
    

    3.写入文件

    #incluede<fstream>
    ofstream outFile;
    outFile.open("carinfa.txt");        //要放入的文件名
    outFile<<...                        //放入的信息
    .
    .
    .
    outFile.close();                    //关闭文件
    

    4.产生0~89之间的随机数

    #include<iostream>
    #include<cstdlib>
    #include<ctime>
    using namespace std;
    int main()
    {
    	double target;
    	srand(time(0));
    	for(int i=0;i<=20;i++)
    	{
    	target=rand()%90;
    	cout<<target<<endl;
    	}
    	return 0;
    }
    

    6.传二维数组

    int show(double* A,int row,int col)
    {
        int i,j;
        double** B=new double*[col];
        for(i=0;i<row;i++)
        {
           B[i]=new double[col];
         }
        for(i=0;i<row;i++)
        {
            for(j=0;j<col;j++)
            {
               B[i][j]=*(A+i*col+j);
               cout<<B[i][j]<<"  ";
            }
            cout<<endl;
         }
         for(i=0;i<row;i++)
         {
            delete[] B[i];
         }
         delete[] B;
     }
    //调用: show(A[0],4,7);
    
  • 相关阅读:
    DS博客作业07--查找
    第五次作业——05图
    第四次作业——04树
    DS博客作业03--栈和队列
    DS博客作业02--线性表
    DS博客作业01--日期抽象数据类型设计与实现
    C语言博客05--指针
    C语言博客作业04--数组
    DS博客作业08--课程总结
    C语言-第0次作业
  • 原文地址:https://www.cnblogs.com/qujingtongxiao/p/9862380.html
Copyright © 2011-2022 走看看