在完成了代码的编写后,很重要的一件事就是要确认我们的code是否可以有效的解决问题,因此测试过程是相当重要的。我们用一个简单的加法程序来说明这一过程。
加法程序的代码如下,我们使用freopen来进行重定向,让原本需要在终端进行的输入变成直接从input.txt文件中进行读取。原本在终端的输出变成输出到ouput.txt文件中。其中input.txt是我们的输入,ouput.txt是空的txt文件。
#include
#include
using namespace std;
int main(){
#ifndef USE_STANDARD_IO
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int a,b,c;
while(cin>>a>>b)
{
c=a+b;
cout<
为了让大家看起来更加熟悉,转换为leetcode常见的结构(看到class Solution有没有种熟悉的感觉)
#include
#include
using namespace std;
class Solution{
public:
int twoSum(int a,int b){
int c;
return a+b;
}
};
int main(){
#ifndef USE_STANDARD_IO
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int a,b,c;
while(cin>>a>>b)
{
Solution s;
c=s.twoSum(a,b);
cout<
使用自己的input.txt编写的输入和输出到output.txt的结果如下
可以看出我们的代码在大数相加的时候,测试结果发生了错误。所以我们可以考虑对输入输出做一个判断,让它的输入输出都在int型的范围内。