Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

C++ Help I am having a problem getting this to print a decimale value if the use

ID: 3935736 • Letter: C

Question

C++ Help

I am having a problem getting this to print a decimale value if the user inputsdecimal values. This is just basic C++ with functions

Problem statement

Prompt the user for two points (x1, y1), (y1, y2). Write a function that calculates the distance between the points

Start with this code:

#include <iostream>

// YOUR CODE GOES BELOW HERE

// TO HERE

// DO NOT CHANGE ANYTHING BELOW HERE

int main() {

double x1, y1, x2, y2;

cout << "Enter x1: ";

cin >> x1;

cout << x1 << endl;

cout << "Enter y1: ";

cin >> y1;

cout << y1 << endl;

cout << "Enter x2: ";

cin >> x2;

cout << x2 << endl;

cout << "Enter y2: ";

cin >> y2;

cout << y2 << endl;

cout << "The distance is ";

cout << distance(x1, y1, x2, y2) << endl;

return 0;

}

My current code:

#include <iostream>
#include <cmath>
using namespace std;

int distance(double x1, double y1, double x2, double y2);

int main() {
  
   double x1, y1, x2, y2;
  
   cout << "Enter x1: ";
   cin >> x1;
   cout << x1 << endl;
   cout << "Enter y1: ";
   cin >> y1;
   cout<< y1 << endl;
   cout << "Enter x2: ";
   cin >> x2;
   cout << x2 << endl;
   cout << "Enter y2: ";
   cin >> y2;
   cout << y2 << endl;
   cout << "The distance is " << distance(x1,y1,x2,y2) << endl;
  
   return 0;
}

int distance(double x1, double y1, double x2, double y2){
  
   double result;
  
   double xRes = (x2 - x1) * (x2 - x1);
   double yRes = (y2 - y1) * (y2 - y1);
   double total = xRes + yRes;
   result = sqrt(total);
  
   return result;
  
}

results:

The result should be in decimal form and not just a whole number

Explanation / Answer

the type of return value of function 'distance' is defined to be 'int', you need to change that. You return double with the function, but since type of return value is defined as int in function definition, it is converted to int before returning,

so change     int distance(double x1, double y1, double x2, double y2){

to                  double distance(double x1, double y1, double x2, double y2){

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote