I'm very new to C++. This is my first assignment, and I'm having trouble printing out (in main()) the final calculated distance d from my function getairdistance(). My program is shown below and I would appreciate any advice!
#include <iostream>
#include <cmath> //for pi
using namespace std;
void getAirDistance(int *ptr, int *ptr1);
int main(){
struct LOC{
char loc_name[50]; //name of a location on earth
double latitude; //latitude of this location
double longitude; //longitude of this location
}; //structure definition
struct LOC location1;
struct LOC location2; //declared two structures
struct LOC *ptr, *ptr1; //declared two pointers
ptr = &location1; //pointer to the first location structure
ptr1 = &location2; //pointer to the second location structure
cout << "Please enter the name of the first location: "; //print statement
cin.getline(location1.loc_name, 50);//use getline to store the first location
cout << "Please enter the latitude (degrees): "; //print statement
cin >> location1.latitude; //use cin to get the first latitude
cout << "Please enter the longitude (degrees): "; //print statement
cin >> location1.longitude; //use cin to get the first longitude
fflush(stdin);
cout << "Please enter the name of the second location: ";
cin.getline(location2.loc_name, 50);
cout << "Please enter the latitude (degrees): ";
cin >> location2.latitude;
cout << "Please enter the longitude (degrees): ";
cin >> location2.longitude; //exact same thing as above
//getAirDistance(location1, location2);
cout << "The air distance between " << location1.loc_name << " and " << location2.loc_name << " is appx. " << " km. "; //final print statement
}
void getAirDistance(int *ptr, int *ptr1){ //function definition
double long1 = *(ptr + 2) * (M_PI/180); //longitude of first location (rad)
double long2 = *(ptr1 + 2) * (M_PI/180); //longitude of second location (rad)
double lat1 = *(ptr + 1) * (M_PI/180); //latitude of first location (rad)
double lat2 = *(ptr1 + 1) * (M_PI/180); //longitude of first location (rad)
double x = (long2 - long1) * cos((lat1 + lat2)/2); //x coordinate difference
double y = lat2 - lat1; //y coordinate difference
int R = 6371; //Radius of the earth
int d = R * sqrt(pow(x, 2) + pow(y, 2)); //distance between the two locations
cout << d;
}
Make your function return the value of d to the caller (ie main()), eg:
int getAirDistance(int *ptr, int *ptr1);
int main(){
...
int d = getAirDistance(...);
cout << ... << d << ...;
return 0;
}
int getAirDistance(int *ptr, int *ptr1){
...
int d = ...;
return d;
}
That being said, your function takes int* pointers as input, but there are no int variables in your main() code that can be passed to the function. Your use of pointer arithmetic suggests that you think +1 and +2 are accessing the 1st and 2nd fields of the LOC struct, but that is not what happens at all. I suspect what you really meant to do is something more like this instead:
#include <iostream>
#include <cmath> //for pi
using namespace std;
struct LOC{
char loc_name[50]; //name of a location on earth
double latitude; //latitude of this location
double longitude; //longitude of this location
}; //structure definition
int getAirDistance(const LOC &loc1, const LOC &loc2);
int main(){
LOC location1;
LOC location2; //declared two structures
cout << "Please enter the name of the first location: "; //print statement
cin.getline(location1.loc_name, 50);//use getline to store the first location
cout << "Please enter the latitude (degrees): "; //print statement
cin >> location1.latitude; //use cin to get the first latitude
cout << "Please enter the longitude (degrees): "; //print statement
cin >> location1.longitude; //use cin to get the first longitude
fflush(stdin);
cout << "Please enter the name of the second location: ";
cin.getline(location2.loc_name, 50);
cout << "Please enter the latitude (degrees): ";
cin >> location2.latitude;
cout << "Please enter the longitude (degrees): ";
cin >> location2.longitude; //exact same thing as above
int d = getAirDistance(location1, location2);
cout << "The air distance between " << location1.loc_name << " and " << location2.loc_name << " is appx. " << d << " km. "; //final print statement
return 0;
}
int getAirDistance(const LOC &loc1, const LOC &loc2){ //function definition
double long1 = loc1.longitude * (M_PI/180); //longitude of first location (rad)
double long2 = loc2.longitude * (M_PI/180); //longitude of second location (rad)
double lat1 = loc1.latitude * (M_PI/180); //latitude of first location (rad)
double lat2 = loc2.latitude * (M_PI/180); //latitude of second location (rad)
double x = (long2 - long1) * cos((lat1 + lat2)/2); //x coordinate difference
double y = lat2 - lat1; //y coordinate difference
int R = 6371; //Radius of the earth
int d = R * sqrt(pow(x, 2) + pow(y, 2)); //distance between the two locations
return d;
}
Related
I have included the code I wrote below. I have created a function that calculates the volume of a cone based on the user's input. This is working as intended.
# include <iostream>
# include <string.h>
# include <string>
using namespace std;
// ConeVolume prototype
float ConeVolume(float radius, float height);
int main()
{
// Establish variables
float radius1;
float height2;
float volumeCone = ConeVolume(radius1, height2);
// User input to define the varibales
cout << "Radius: ";
cin >> radius1;
cout << "Height: ";
cin >> height2;
// Return variable using the ConeVolume function
cout << endl << "Cone Volume: " << volumeCone;
return 0;
}
// Function that calculates the volume of a Cone
float ConeVolume(float radius, float height)
{
float pi = 3.14;
float volume = (pi/3)*(radius * radius) * (height);
return volume;
}
My question... if I were to call the function by outputting the variable "float ConeVolume" as below, why does the program return '0'? Can I not set the value of a variable equal to a function?
// Return variable using the volumeCone float variable
cout << endl << "Cone Volume: " << volumeCone;
You've simply made a silly mistake. You've called the 'ConeVolume' function before taking user input. So, only garbage values are being passed to the function.
# include <iostream>
# include <string.h>
# include <string>
using namespace std;
// ConeVolume prototype
float ConeVolume(float radius, float height);
int main()
{
// Establish variables
float radius1;
float height2;
//wrong code here
// you've called the function before taking input of radius1 and height2
//float volumeCone = ConeVolume(radius1, height2);
// User input to define the varibales
cout << "Radius: ";
cin >> radius1;
cout << "Height: ";
cin >> height2;
// Correct code:
// Call the function after taking input
float volumeCone = ConeVolume(radius1, height2);
// Return variable using the ConeVolume function
cout << endl << "Cone Volume: " << volumeCone;
return 0;
}
// Function that calculates the volume of a Cone
float ConeVolume(float radius, float height)
{
float pi = 3.14;
float volume = (pi/3)*(radius * radius) * (height);
return volume;
}
Hope this helped.
The program return 0 because the value volumeCone is not being updated after you changed the values of radius1 and height2.
You have to call the function coneVolume() again, or better yet just call it after you define radius1 and height2.
int main()
{
// Establish variables
float radius1;
float height2;
// User input to define the varibales
cout << "Radius: ";
cin >> radius1;
cout << "Height: ";
cin >> height2;
float volumeCone = ConeVolume(radius1, height2);
// Return variable using the ConeVolume function
cout << endl << "Cone Volume: " << volumeCone;
return 0;
}
Insert the line
volumeCone = ConeVolume(radius1, height2);
after the line
cin >> height2;
And change line
float volumeCone = ConeVolume(radius1, height2);
to
float volumeCone;
Every time I run the program, using the exact same values (25 for diameter and 5 for depth), I am getting different values for water_price and I'm not sure why.
Some of the outcomes:
$6.62256e+07 is the total cost.
$0 is the total cost.
$2.43411e-27 is the total cost.
I don't know if I am dealing with values in memory not playing well with each other, not flushing or what.
Why are the outcomes different every time I run this program?
#include <iostream>
#define PI 3.1416
#define WATER_COST 1.80
using std::cout;
using std::cin;
using std::endl;
int main() {
float pool_diameter, pool_depth;
float pool_radius = pool_diameter / 2;
float pool_volume_sq_inches = (PI * pool_radius * pool_radius * pool_depth) * 1728;
float pool_gallons = pool_volume_sq_inches / 231;
float water_price = (pool_gallons / 748) * WATER_COST;
cout << "Enter the pool diameter: ";
cin >> pool_diameter;
cout << "\nEnter the pool depth: ";
cin >> pool_depth;
cout << "\n$" << water_price << " is the total cost." << endl;
return 0;
}
See how we need to declare the variables to begin with, then when you ask for input it will be stored in those variables, and then you can continue on with the calculations you need.
#include <iostream>
#define PI 3.1416
#define WATER_COST 1.80
using std::cout;
using std::cin;
using std::endl;
int main() {
float pool_diameter = 0.0;
float pool_depth = 0.0;
cout << "Enter the pool diameter: ";
cin >> pool_diameter;
cout << "\nEnter the pool depth: ";
cin >> pool_depth;
float pool_radius = pool_diameter / 2;
float pool_volume_sq_inches = (PI * pool_radius * pool_radius * pool_depth) * 1728;
float pool_gallons = pool_volume_sq_inches / 231;
float water_price = (pool_gallons / 748) * WATER_COST;
cout << "\n$" << water_price << " is the total cost." << endl;
return 0;
}
You may want to get the inputs soon after the declaration.
float pool_diameter, pool_depth;
cout << "Enter the pool diameter: ";
cin >> pool_diameter;
cout << "\nEnter the pool depth: ";
cin >> pool_depth;
Rest code would work the way it is.
A good practice would be to initialize your variables like Omid-CompSci has answered here.
Statement float pool_radius = pool_diameter / 2; is executed before
cin >> pool_diameter;. Default value(garbage value) is used every time to calculate the pool_radius that is reason for different values in different runs.
change the order.
I am trying to get the averages of a set of numbers in an array and I am getting -nan(ind) as my output. I am unsure of what is causing this issue. Here is the code that I have written so far in C++:
#include "pch.h"
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
void input_from_file(ifstream & inFile, char * item, char * name, double & price, double & cost, double & material_cost);
double array_price[50], array_total_cost[50];
double price, base_cost, material_cost;
int cnt = 0, i;
double calAverage(double arr[], int s);
char item[2]{ "" };
char name[21];
double total_cost = base_cost + material_cost;
double profit = price - total_cost;
void File_Input(ifstream & Main_File)
{
do {
string File_Name;
cout << "Please enter the file name including extension: ";
cin >> File_Name;
Main_File.open(File_Name);
} while (!Main_File);
}
void File_Read(ifstream & The_File)
{
cout << setw(29) << left << "Name" << right << setw(10) << "Price" << setw(10) << "Cost" << setw(10) << "Profit" << "\n" << endl;
string Typed_File;
int increment = { 0 };
while (!The_File.eof())
{
input_from_file(The_File, item, name, price, base_cost, material_cost);
total_cost = base_cost + total_cost;
profit = price - total_cost;
array_total_cost[increment] = total_cost;
array_price[increment] = price;
increment++;
cout << setw(29) << left << name << right << setw(10) << price << setw(10) << total_cost << setw(10) << profit << endl;
};
cout << "\n\nThe average price is " << calAverage(array_price, cnt);
cout << "\nThe average cost is " << calAverage(array_total_cost, cnt) << " \n";
}
void input_from_file(ifstream & inFile, char * item, char * name, double & price, double & base_cost, double & material_cost)
{
inFile >> item;
inFile >> name;
inFile >> price;
inFile >> base_cost;
inFile >> material_cost;
array_price[cnt] = price;
array_total_cost[cnt] = base_cost + material_cost;
}
double calAverage(double arr[], int s)
{
int i;
double sum = 0;
for (i = 0; i < s; i++)
{
sum += arr[i];
}
return (sum/(double)(s));
}
int main()
{
ifstream The_File;
File_Input(The_File);
File_Read(The_File);
}
Here is the file that I am trying to read from:
food2.txt
D WhiteWine 3.5 0.75 0.0
F Courgetts 751.88 125.31 75.19
F BroccoliAuRoquefort 860.63 227.81 111.38
D RedWine 357.88 76.69 0.0
F CoqAuVin 774.38 129.06 77.44
F GratinDePates 886.13 234.56 114.68
F GnocchiAuxLegumes 368.38 78.94 55.23
F Raviole 796.88 132.81 79.69
F PatesFraichesAuNoix 911.63 241.31 117.98
D Milk 378.88 81.19 0.0
F RizAuCumin 819.38 136.56 81.94
F GratinDePolenta 937.13 248.06 121.28
D Coffee 389.38 83.44 0.0
F RisottoAuxAsperges 841.88 140.31 84.19
F GateauDePommes 962.63 254.81 124.58
D Tea 3.00 .69 0.0
F SoupeD'Epeautre 864.38 144.06 86.44
F Tartiflette 988.13 261.56 127.88
D WaterWithGas 4.38 5.23 0.0
F Aligot 886.88 147.81 88.69
F abcdefghijklmnopqrst 999.99 268.31 131.18
Here is the full output that I am getting:
output
Any help is appreciated. Thank you
Make sure you add cnt ++; to your while loop. Also try to stay away from global variables if possible. And as previously stated, here is a reason why eof is bad in a while loop
Not incrementing cnt leaves it at zero. This leads to calculating 0.0 / 0 which is NaN.
Here I have my code to calculate the distance between the user inputted points, and the calculateDistance function should take in two pointers, I feel like I had it setup right, but when I run the code I get this error: bash: line 12: 25372 Segmentation fault $file.o $args
Code:
struct Point{
float x;
float y;
};
float calculateDistance(struct Point *p1, struct Point *p2){
float *fx, *fy;
*fx = (*p1).x - (*p2).x;
*fy = (*p1).y - (*p2).y;
return sqrt((*fx * *fx) + (*fy * *fy));
}
int main()
{
struct Point *p1, *p2, q, w;
p1 = &q;
p2 = &w;
//float distance;
cout << "Enter coordinate for p1x: " << endl;
cin >> (*p1).x;
cout << "Enter coordinate for p1y: " << endl;
cin >> (*p1).y;
cout << "Enter coordinate for p2x: " << endl;
cin >> (*p2).x;
cout << "Enter coordinate for p2y: " << endl;
cin >> (*p2).y;
//distance = calculateDistance(*p1, *p2);
cout << "Distance between points: " << calculateDistance(p1, p2) << endl;
return 0;
}
One fault is in function calculateDistance. Please change it as
float calculateDistance(struct Point *p1, struct Point *p2){
float fx, fy;
fx = (*p1).x - (*p2).x;
fy = (*p1).y - (*p2).y;
return sqrt((fx * fx) + (fy * fy));
}
I have to create a program to calculate charges for airfare. It's a simple program so far and I am not done adding to it, but every time I run it the result turns out to be 0. Is there something missing in my code? I am a beginner and I would appreciate any advice on improving my code. Thank you.
#include <iostream>
using namespace std;
void main () {
int distance = 0;
int num_bags= 0;
int num_meals= 0;
double distance_price = distance * 0.15;
double bag_price = num_bags * 25.00;
double meal_price = num_meals * 10.00;
double total_airfare = 0.00;
cout << "CorsairAir Fare Calculator" << endl;
cout << "Enter the distance being travelled: " << endl;
cin >> distance;
cout << "Enter number of bags checked: " <<endl;
cin >> num_bags;
cout << "Enter the number of meals ordered: " << endl;
cin >> num_meals;
total_airfare = (distance_price + bag_price + meal_price);
cout << total_airfare;
}
Your confusion is completely understandable - the piece you're missing is that when you assign a variable, you're assigning the left side to the result of the right side at that moment in time. It's not like algebra, where you say f(x) = x + 5 and f(x) is always whatever x + 5 is.
So, you assign double distance_price = distance * 0.15 when distance is 0 (which you just initialized). distance_price remains 0 even after you ask for input and change distance.
Do your price calculations after you ask for input, and everything will work just fine.
You are calculating the distance_price bag_price meal_price with default values i.e. 0 not with the value which you took from user.
Below code works fine and you won't see the issue.
#include <iostream>
using namespace std;
// My compiler did not allow void main so used int main
int main () {
int distance = 0;
int num_bags= 0;
int num_meals= 0;
double distance_price ;
double bag_price ;
double meal_price;
double total_airfare;
cout << "CorsairAir Fare Calculator" << endl;
cout << "Enter the distance being travelled: " << endl;
cin >> distance;
cout << "Enter number of bags checked: " <<endl;
cin >> num_bags;
cout << "Enter the number of meals ordered: " << endl;
cin >> num_meals;
distance_price = distance * 0.15;
bag_price = num_bags * 25.00;
meal_price = num_meals * 10.00;
total_airfare = 0.00;
total_airfare = distance_price + bag_price + meal_price;
cout << total_airfare;
return 0;
}
Result
CorsairAir Fare Calculator
Enter the distance being travelled:
200
Enter number of bags checked:
2
Enter the number of meals ordered:
2
100