Write a program which prompts a user for 5 2-D (x,y) coordinates and writes them
ID: 3794670 • Letter: W
Question
Write a program which prompts a user for 5 2-D (x,y) coordinates and writes them to a file "points.txt”, one point (x,y) coordinate pair per line. Be sure to close the file before exiting the program. (Don’t write parentheses or put a comma, just write 2 floating point values per line.)
Write a second program to open the same file ("points.txt"), read the two vectors (10 numbers) back in, calculates whether the points are inside a circle centered at the origin with radius 20. (i.e., is the Euclidean distance (square root of sum of squares) less than 20?) Have your program print out a to the console the original coordinates, the length of each vector from the origin to the point, and whether it is inside a circle with radius 20.
Explanation / Answer
Please use DevC++ to run them
Program 1
#include<iostream>
#include<fstream>
using namespace std;
int main(int argc, char* argv[])
{
//create an output file object
ofstream outfile;
float num;
outfile.open("points.txt", std::fstream::app); //append mode
for(int i=0; i<5;i++)
{
cout<<" Enter x:";
cin>>num;
outfile<<num<<" ";
cout<<" Enter y:";
cin>>num;
outfile<<num<<endl;
}
cout<<" Added data completed";
outfile.close(); //close the file
return 0;
}
Program 2:
#include<string>
#include<iostream>
#include<fstream>
#include<math.h>
using namespace std;
int main(int argc, char* argv[])
{
ifstream fin;
fin.open("points.txt",fstream::in);
if(!fin)
{
cout<<" Unable to read file";
}
float x,y,length;
fin.clear();
fin.seekg(0,ios::beg);
cout<<"x: y: length: ";
while(fin>>x)
{
fin>>y;
length=sqrt(x*x+y*y);
if(length<=20)
{
cout<<x<<" "<<y<<" "<<length<<endl;
}
}
fin.close();
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.