笔试编程题输入输出模板备忘

C++:

借用C++中的new/delete

#include "stdlib.h"
#include <iostream>
using namespace std;

int main()
{
    int m, n;
    //cout << "请输入行和列:";
    cin >> m >> n;

    //动态开辟空间  
    int **p = new int*[m]; //开辟行  
    for (int i = 0; i < m; i++)
        p[i] = new int[n]; //开辟列  

    //cout << "请输入数据:";
    for (int i = 0; i < m; i++)
        for (int j = 0; j < n; j++)
            cin >> p[i][j];

    //cout << "输出数据:" << endl;
    for (int i = 0; i < m; i++)
    {
        for (int j = 0; j < n; j++)
            cout << p[i][j];
        cout << endl;
    }

    //释放开辟的资源  
    for (int i = 0; i < m; i++)
        delete[] p[i];
    delete[] p;
    system("pause");
    return 0;
}

STL中的vector

#include "stdlib.h"
#include <iostream>
#include<vector>
#include <iomanip>
using namespace std;

int main()
{
    int m, n;
    //cout << "请输入行和列:";
    cin >> m >> n;

    //注意下面这一行:vector <int后两个 "> "之间要有空格!否则会被认为是重载 "> > "。   
    vector<vector<int> > p(m, vector<int>(n));

    //cout << "请输入数据:";
    for (int i = 0; i < m; i++)
        for (int j = 0; j < n; j++)
            cin >> p[i][j];

    //cout << "输出数据:" << endl;
    for (int i = 0; i < m; i++)
    {
        for (int j = 0; j < n; j++)
            cout << setw(3) << p[i][j];
        cout << endl;
    }
    system("pause");
    return 0;
}

多行输入,Ctrl+Z可退出

int main()
{
    int n, m;
    vector<double> test;
    while (cin>>n>>m)//循环多行输入,回车换行,Ctrl+Z可结束循环
    {
        test.push_back(qiuhe(n, m));
    }
    for (int i = 0; i < test.size(); ++i)
    {
        cout << fixed << setprecision(2) << test[i] << endl;
    }
    return 0;
}

Ctrl+Z在Windows下为文件结束符EOF(End of File),Unix/Linux下为组合键Ctrl+D

scanf函数的原型是返回输入的个数:

int test2 = scanf("%d%d", &n, &m);//test2 =2

输出小数,保留两位精度

// setprecision example
#include <iostream>     // std::cout, std::fixed
#include <iomanip>      // std::setprecision
using namespace std;

int main () {
  double f =3.14159;
  cout << setprecision(5) << f << '\n'; //3.1416
  cout << setprecision(9) << f << '\n'; //3.14159
  cout << fixed;
  cout << setprecision(5) << f << '\n'; //3.14159
  cout << setprecision(9) << f << '\n'; //3.141590000
  return 0;
}
printf("%.2f\n", test[i]);
//cout << fixed << setprecision(2) << test[i] << endl;
%f 对应 float 
%lf 对应 double 
%Lf 对应 long double 
%e以科学计数法显示 
%g在%e和%f中择短显示






  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值