zoukankan      html  css  js  c++  java
  • 04373 C++程序设计 2019版 第一章习题五、程序设计题

    题目:

    1、编写一个程序,将从键盘输入的n个字符串保存在一个一维数组A中。在输入字符串之前,先输入n的值。要求,数组A需要动态申请空间,程序运行结束前再释放掉。

    #include <iostream>
    
    using namespace std;
    
    int main(){
        cout<<"请输入字符串个数:";
        int n;
        //输入n
        cin>>n;
        //动态申请字符串数组,以n作为数组长度
        string *A = new string[n];
        for(int i=0;i<n;i++){
            cout<<"请输入第"<<i+1<<"个参数:";
            cin>>A[i];
        }
        cout<<"开始打印数组"<<endl;
        for(int j=0; j<n; j++){
            cout<<"A["<<j<<"]="<<A[j]<<endl;
        }
    	//释放数组内存
        delete []A;
        return 0;
    }
    

    输出:

    2、在题目1的基础上,输出n个字符串中最长的和最短的串,计算n个串的平均长度并输出结果。

    #include <iostream>
    
    using namespace std;
    
    int main(){
        cout<<"请输入字符串个数:";
        int n;
        cin>>n;
        string *A = new string[n];
        for(int i=0;i<n;i++){
            cout<<"请输入第"<<i+1<<"个参数:";
            cin>>A[i];
        }
        cout<<"开始打印数组"<<endl;
        //最长串
        string longest="";
        //最短串
        string shortest="";
        //总长度
        int totalLen=0;
    
        for(int j=0;j<n;j++){
            cout<<"A["<<j<<"]="<<A[j]<<endl;
            //统计总长度
            totalLen+=A[j].length();
            //首次循环直接为最长串与最短串设置当前循环字符串
            if(longest==""){
                longest=A[j];
            }
            if(shortest==""){
                shortest=A[j];
            }
            //判断更新最长与最短串
            if(longest.length()<A[j].length()){
                longest=A[j];
            }
            if(shortest.length()>A[j].length()){
                shortest=A[j];
            }
        }
        cout<<"最长串:"<<longest<<"	最短串:"<<shortest<<"	总长度:"<<totalLen<<"	平均长度:"<<totalLen/n<<endl;
        delete []A;
        return 0;
    }
    

    输出:

  • 相关阅读:
    poj 3255
    (DP) bzoj 2091
    (最短路) bzoj 2118
    (点双联通分量) poj 2942
    (树直径) bzoj 1509
    (离线处理+BFS) poi Tales of seafaring
    (并查集+DFS) poi guilds
    (记忆话搜索)POI Fibonacci Representation
    (DP) POI Bytecomputer
    (DP) bzoj 1296
  • 原文地址:https://www.cnblogs.com/hellxz/p/14988951.html
Copyright © 2011-2022 走看看