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中择短显示