[原创]一道基本ACM试题的启示——多个测试用例的输入问题。

Problem Description

输入两点坐标(X1,Y1),(X2,Y2),计算并输出两点间的距离。
Input
输入数据有多组,每组占一行,由4个实数组成,分别表示x1,y1,x2,y2,数据之间用空格隔开。
Output
对于每组输入数据,输出一行,结果保留两位小数。
Sample Input
0 0 0 1
0 1 1 0
Sample Output
1.00
1.41

学过任何一门编程语言的人,做这道题应该是5分钟解决战斗吧。就像我一开始这样写
#include<iostream>
#include "stdio.h"
#include<math.h>
using namespace std;
int main()
{
	float a,b,x,y;
	float dis;
	cin>>a>>b>>x>>y;
	dis=sqrt((a-x)*(a-x)+(b-y)*(b-y));
	printf("%.2f",dis);
	return 0;
}

      然后提交,系统就会提示错误答案。一开始一直在从数据类型和范围上找,始终没能解决,但是仔细观察,会发现测试用例是写了两组,而自己写的只能测试一组,于是就引出了一个问题——多个测试用例的输入问题。

有问题就改,于是将代码重写成

#include<iostream>
#include "stdio.h"
#include<math.h>
using namespace std;
int main()
{
	float a[10],b[10],x[10],y[10];
	float dis;
	int i=0,j=0;
	while(cin>>a[i]>>b[i]>>x[i]>>y[i])//先输入所有用例
	{
		i++;
	}
	for(j=0;j<i;j++)//再一个一个计算,输入循环的i用来控制次数
	{
	    dis=sqrt((a[j]-x[j])*(a[j]-x[j])+(b[j]-y[j])*(b[j]-y[j]));
	    printf("%.2f",dis);
	    cout<<endl;
	}
	return 0;
}

  提交,会发现Accept。

从网上找到一个表,觉得不错,转载过来。

 

Language

C

C++

To read numbers

int n;
while(scanf("%d", &n) != EOF)
{
  ...
}

int n;
while (cin >> n)
{
  ...
}

To read characters

int c;
while ((c = getchar()) != EOF)
{
  ...
}

char c;
while (cin.get(c))
{
  ...
}

To read lines

char line[1024];
while(gets(line))
{
  ...
}

string line;
while (getline(cin, line))
{
  ...
}

 

posted @ 2016-04-08 18:00  LibraSun  阅读(932)  评论(0编辑  收藏  举报