Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I always programmed on xcode, but after finally switching back to PC, I decided to use Visual studios; however, one problem I'm encountering is that it won't read my whole program at times. For example. I could have a program aht just displays "Hello", and it'll show that, but when I modify it, and add other things to the same program it won't recognize the rest of the program and when I build, and run it it'll just display "Hello", even though there's other lines of code.
Here's a program I was trying write
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
void DisplayInput(string[], string[], char [], double[], double[], double[], int);
void Calculation(double, double, double, double[], double[], double, double, int);
int main()
{
int const size = 3;
string F_name[size], L_name[size];
char Mi[size];
double HoursWorked[size], Rate[size], Gross[size], Net[size];
double StateTax, FederalTax, UnionFees, Sum, Avg;
DisplayInput(F_name, L_name, Mi, HoursWorked, Rate, Gross, size);
Calculation(StateTax, FederalTax, UnionFees, Gross, Net, Sum, Avg, size);
system("pause");
}
void DisplayInput(string F_name[], string L_name[], char Mi[], double HoursWorked[], double Rate[], double Gross[], int size)
{
for (int i = 0; i < size; i++)
{
cout << " What's your first name " << endl;
cin >> F_name[i];
cout << "What's youtr last name? " << endl;
cin >> L_name[i];
cout << "Enter your middle initials. " << endl;
cin >> Mi[i];
cout << "How many hours did you work " << endl;
cin >> HoursWorked[i];
cout << "What is your hourly rate " << endl;
cin >> Rate[i];
double TimeHalf = 1.5;
if (HoursWorked[i] < 0 || HoursWorked[i] > 60)
{
cout << " Wrong entry " << endl;
}
if (Rate[i] < 0 || Rate[i] > 50)
{
cout << "Number needs to be between 1 and 50 " << endl;
}
if (HoursWorked[i] <= 40)
{
Gross[i] = HoursWorked[i] * Rate[i];
}
else if (HoursWorked[i] > 40)
{
Gross[i] = HoursWorked[i] * (Rate[i] * TimeHalf);
}
}
}
void Calculation(double StateTax, double FederalTax, double UnionFees, double Gross[], double Net[], double Sum, double Avg, int size)
{
StateTax = Gross[size] * 0.06;
FederalTax = Gross[size] * 0.12;
UnionFees = Gross[size] * 0.02;
Net[size] = Gross[size] - (StateTax + FederalTax + UnionFees);
Sum = +Gross[size];
Avg = Sum / size;
}
Yet when I run it, all I get is it asking me for the name, last name, and not the hours worked or rate, or any of the other lines of code I have in this program. Any suggestions as to what might be causing this? It's happened a few times this week, and a work around was to save the program, and restart Visual Studios, but I did that again today and it's not working.
Sounds like you're project isn't building correctly
if you see this message box it means that there were errors in your code
if you just press yes, it will run the previously successfully compiled build. so it sounds like you are doing this. If you see this message, press no and check your code.
Related
c++ and I'm trying to figure out why my code returns 0's from a few statements after the user inputs some float numbers. I'm not sure why. Maybe someone can help:
This is what I get after running my method and answering the questions before it:
The number of gallons of paint required is: 0 gallons
Hours of labor that is required: 0 hours
.
Also ignore the () around my # in the beginning. I will put periods between lines to make it look neater on this website.
/**
* A painting company has determined that for every 160 square feet of wall
space, one gallon of paint and 3 hours of labor are required.
* The company charges the $28.00 per hour for labor.
* Design a modular program that allows the user to enter the number of rooms
that are to be painted,
* the approximate square feet of wall space in each room (may differ from room
to room), and the price per gallon of paint.
* It should then create a report that includes a fancy company header and
displays the following information:
* The number of gallons of paint required: (Rounded up to the next full
gallon)
* The hours of labor required:
* The cost of the paint:
* The labor charges:
* Total cost of the paint job:
* Requirements:
* Input validation: The program should not accept a value less than 1 or
more than 12 for the number of rooms
* Should not accept a value less than 100 for the square
footage of a room.
* Should not accept a value less than $10.00 or more
than $25.00 for the price of a gallon of paint
*
* Lets do this...
*/
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
float priceOfGallon(float);
float numberOfGallons(float, float);
float totalWallArea(float, float, float);
float laborHours(float, float);
void fancyCompanyHeader();
int main() {
float area;
float totalArea;
float min_labor = 3;
float number_of_rooms;
float number_of_gallons;
float price_of_gallon;
totalWallArea(area, totalArea, number_of_rooms);
priceOfGallon(price_of_gallon);
numberOfGallons(number_of_gallons, totalArea);
laborHours(number_of_gallons, min_labor);
fancyCompanyHeader();
return 0;
}
// function that gets the number of gallons needed for the total area
float numberOfGallons(float number_of_gallons, float totalArea) {
number_of_gallons = (totalArea / 160.0);
std::cout << "The number of gallons of paint required is: " <<
number_of_gallons << " gallons" << std::endl;
}
float priceOfGallon(float price_of_gallon){
std::cout << "Please enter the price per gallon: " << std::endl;
cin >> price_of_gallon;
while(price_of_gallon < 10.00 || price_of_gallon > 25.00) {
std::cout << "The price should be between $10.00 and $25.00. Please try again: " << std::endl;
cin >> price_of_gallon;
}
}
float totalWallArea(float area, float totalArea, float number_of_rooms) {
std::cout << "Please enter the number of rooms that needs to be painted:" <<
std::endl;
std::cin >> number_of_rooms;
while(number_of_rooms < 1)
{
cout << "Number of rooms must be at least one. Please try again: " <<
std::endl;
cin >> number_of_rooms;
}
for(float i = 1; i <= number_of_rooms; i++)
{
cout << "Please enter the square feet of wall space needed for Room " <<
i << std::endl;
cin >> area;
while(area < 100)
{
std::cout << "The area should be 100 or greater. Please try again: "
<< std::endl;
cin >> area;
}
totalArea += area;
}
}
// I will finish this method later
float laborHours(float number_of_gallons, float min_labor) {
min_labor = number_of_gallons * 28.00;
std::cout << "Hours of labor that is required: " << min_labor << " hours "
<< std::endl;
return min_labor;
}
You need to make all of those variables you are modifying global (Declared outside of int main()). In C++, when you give a function a variable, it will just copy the contents of the variable into the function's variables: the original variable passed in remains constant. Thus, your uninitialized floats default to 0 and are not changed by any of the functions, so when they are given to the laborHours function or numberOfHours function, 0s are passed into each.
Example with much better practices than in your code (it's ok, everyone starts by writing atrocious code) :
#include <iostream>
int walls,rooms,total_walls; //It only makes sense if all of these are integers.
//These are global declarations, they can be modified by any function in the program
void input_walls() {
/* Functions are notated as so in C++:
{return type} {function_name}({input},{input},...)
It's pointless to annotate functions that don't return anything
with a declaration of a float return type (they'll just return 0 */
std::cin >> walls;
while(walls < 0) {
std::cout << "Please input a positive amount of walls per room.";
std::cin >> walls;
}
}
void input_rooms() {
std::cin >> rooms;
while(rooms < 0) {
std::cout << "Please input a positive amount of rooms";
std::cin >> rooms;
}
}
void calculate_result() {
total_walls = walls*rooms;
}
void output_result() {
std::cout << "I'll need to paint " << total_walls << " walls!" << std::endl;
}
int main() {
input_walls();
input_rooms();
calculate_result();
output_result();
}
This still isn't the best way to write this, but it's still the exact same thing you were trying to do. Now try rewriting what you were trying to do in this style!
TLDR/Quick fix: Make the variable definitions global, cut out the arguments from the functions.
I'm currently learning about functions in C++ and am currently working on a homework assignment with functions being the main thing.
Currently, I'm trying to make a grade calculator with every operation of the process being split into a function of its own.
Here's the code:
#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
using namespace std;
void getHWGrades(int homeworks[], int size)
{
cout << "\nEnter the grades, out of 100 points, for the 9 homeworks you completed." << endl;
cout << "Note that Homework 10 is given to you for free, but is the same grade \nas homework 9.\n" << endl;
for (int i = 0; i < 9; i++)
{
cout << "Homework " << i + 1 << ": ";
cin >> homeworks[i];
while (homeworks[i] > 100 || homeworks[i] < 0)
{
cout << "Invalid grade, input homework grade again: ";
cin >> homeworks[i];
}
}
homeworks[9] = homeworks[8];
cout << "Homework 10: " << homeworks[9];
}
double quizAverage()
{
double quizPts;
cout << "Input your in class quiz average: ";
cin >> quizPts;
return quizPts;
}
double labAverage()
{
double labPts;
cout << "Input your lab average: ";
cin >> labPts;
return labPts;
}
double teamProject()
{
double teamPts;
cout << "Input your team project grade: ";
cin >> teamPts;
return teamPts;
}
int exam1()
{
int exam1Pts;
cout << "Input your exam1 grade: ";
cin >> exam1Pts;
return exam1Pts;
}
int exam2()
{
int exam2Pts;
cout << "Input your exam2 grade: ";
cin >> exam2Pts;
return exam2Pts;
}
double hwAverage(int homeworks[], int size)
{
double total = 0;
double homeworkAverage = 0;
for (int i = 0; i < size; i++)
{
total = total + homeworks[i];
}
homeworkAverage = (total*1.0) / 10;
return homeworkAverage;
}
double currentPoints(double& quizPts, double& labPts, double& teamPts, double& homeworkAverage, int& exam1Pts, int& exam2Pts)
{
double totalPts = ((quizPts / 100.0) * 10) + ((labPts / 100.0) * 10) + ((teamPts / 100.0) * 15) + ((homeworkAverage / 100.0) * 20) + ((exam1Pts / 100.0) * 10) + ((exam2Pts / 100.0) * 15);
cout << "\nYour current points (out of the 80 total available), stand at: " << totalPts;
return totalPts;
}
double currentAverage(double& totalPts)
{
double availableAverage = totalPts*(100.0 / 80);
cout << "\nYour current average is: " << availableAverage;
return availableAverage;
}
int main()
{
// keep the console from closing in visual studio
char charer;
double totalPts;
double quizPts, labPts, teamPts, homeworkAverage;
int exam1Pts, exam2Pts;
const int ARRAY_SIZE = 10;
int hwArray[ARRAY_SIZE];
getHWGrades(hwArray, ARRAY_SIZE);
quizAverage();
labAverage();
teamProject();
exam1();
exam2();
currentPoints(quizPts, labPts, teamPts, homeworkAverage, exam1Pts, exam2Pts);
currentAverage(totalPts);
cin >> charer;
}
My issue, which I believe lies in the functions currentPoints and currentAverage, is that when I run this totalPts outputs as -5.09078e+61 and as a follow up result with the currentAverage function, availableAverage outputs as -1.157e+62.
I'm sure that the issue has to do with how I'm passing the values from function to function (which I doubt I'm doing correctly).
How would I go about fixing this issue?
Thank you in advance.
You need to store the return value from currentPoints() function, like this.
totalPts = currentPoints(quizPts, labPts, teamPts, homeworkAverage, exam1Pts, exam2Pts);
currentAverage(totalPts);
Reason is, you declared "totalPts" as local variable in currentPoints().
"Local variables has function scope only, it is undefined to main function".
Do this for all other
functions(quizAverage,labAverage,teamProject,exam1,exam2, hwAverage,currentAverage)
I hope, this will solve the issue !!!
The problem is not about functions, it's about variables.
Let's take quizPts for instance:
In the main method, you declare this variable, but then you don't do anything with it before sending it to currentPoints. Therefore it has an undefined value when you do so (undefined often looks like random in C).
The other variable quizPts you use in quizAverage have the same name but is not the same for the compiler.
Try in your main:
quizPts = quizAverage();
You asked
How would I go about fixing this issue?
And the answer is "Use the debugging tool with "watches" window open in your favorite IDE".
It's always very difficult to find an error simply by re-reading the code, but in the debugger you can see all the values of your variables at each moment of time. Specifically, in this example, you would realize that your variables have garbage values from the very beginning (are not initialized), and this value never changes.
Using this approach you could find the reason yourself in time less than necessary to write this SO question. I hope this will help you to save your time in future.
The problem is you use the variables such as quizPts and labPts without storing any value in them. In your case, you have to store the return value of the function to the corresponding variable before using it. For example, do the same as the following statement:
quizPts = quizAverage();
I'm in beginning computer science class and we're currently learning about functions, however I thought that I would take it one step further and start teaching myself about objects early on. I tried to make this Average game score calculator, however upon entering the values 10, 20, 30 and 40 then entering the loop sentinel value of -999. Where I should get an average of 25, as its 100/4, I get 80. I've played around with it quite a bit but just cannot figure out what I'm doing wrong exactly -- I try not to ask for help anymore unless I really can't figure something out after a few hours of reading through google and my books. So any help would be much appreciated :)
EDIT: My question is: Why when I enter all these values do they not go through the proper route and get a correct average? (This is my first time ever even attempting to use objects and don't know very much about how to use them, but I figured trial and error would help me learn.)
Thank you in advanced!
P.S I'm new here, but I hope that I formatted this question correctly as to not get anyone mad at me again. Oh and I know I haven't used the iomanip or string libraries yet, however I plan to in the future so I just left them in there.
//COMSCI 110
//HUNTER DURNFORD
//INPUT
//SPECIAL COMPILER FUNCTIONS
//NONE
//PROCESSING
//
//DATA
//
//LIBRARIES
#include <iomanip>
#include <string>
#include <iostream>
using namespace std;
//PROGRAMMER DEFINED FUNCTIONS
//introduction
//
//Object Classes
//AvgScoreCalculator
//Object class
class AvgScoreCalculator
{
private:
//double total_Scores = game_Scores;// The total scores
//double score_Average = total_Scores / score_Count; // the average equation
public:
double total_Scores; // the total that gets input into the average function
double score_Average; // the average of all the games
double score_Count; // the counter for each individual game entry
double game_Scores; // the scores for the individual games
//char exit_Value;
};//end class
//introduction function
void introduction()
{
cout << "Enter any amount of characters and this program will encrypt them." << endl;
cout << "By Hunter Durnford." << endl;
cout << "Editor(s) used: XCODE TEXT EDITOR and JNotePad 2\n";
cout << "Compiler(s) used: XCODE\n";
cout << "File: " << __FILE__ << endl;
cout << "Complied: " << __DATE__ << " at " << __TIME__ << endl << endl;
}//introduction
//function to get scores from user
double getScoreFunction()
{
double score_Count = 0.0;
double gameScores = 0.0;
double total_Scores = 0.0;
while(true)
{
cout << "What score would you like to input? Or type -999 to exit. ";
cin >> gameScores;
if(gameScores == -999)
{
break;
}
score_Count = score_Count + 1;
gameScores = gameScores + gameScores;
total_Scores = gameScores;
}
return total_Scores;
}//end score function
//Average of all the scores function
double getAverageFunction(double total_Scores, double score_Count)
{
double average_Score;
average_Score = total_Scores / score_Count;
return average_Score;
}
//main program
int main()
{
introduction();
AvgScoreCalculator average_Score; //Declaring the object under the class
//set the integers for the average_score object
average_Score.score_Count = 0.0;
average_Score.game_Scores = 0.0;
average_Score.score_Average = 0.0;
average_Score.total_Scores = 0.0;
average_Score.game_Scores = getScoreFunction();
average_Score.score_Average = getAverageFunction(average_Score.total_Scores, average_Score.score_Count);
cout << "The average of all the game scores is: " << average_Score.game_Scores << endl;
}
(leaving apart problems with the precision of doubles that has been pointed out in the comments)
Problem here:
score_Count = score_Count + 1;
gameScores = gameScores + gameScores;
total_Scores = gameScores;
play it in your head:
gameScores=0.0
total_Scores=0.0
... now you read 10
gameScores=10.0
gameScore=gameScore + gameScore -> 10.0 + 10.0 = 20.0
total_Scores = gameScore = 20.0
... next loop just overwrites.
should be:
score_Count = score_Count + 1;
total_Scores += gameScores;
in addition, score_Count is a local variable of getScoreFunction()... so its changes do not affect the average_Score.score_Count used for the average calculation.
So im still pretty new to C++ and have been doing a program for a while now. I think I am slowly getting it but keep getting an error "Intellisense: operand of '*' must be a pointer." on line 36 column 10. What do I need to do to fix this error? Im going to get to the other functions as i finish each one so sorry for the extra function declaration
// This program will take input from the user and calculate the
// average, median, and mode of the number of movies students see in a month.
#include <iostream>
using namespace std;
// Function prototypes
double median(int *, int);
int mode(int *, int);
int *makeArray(int);
void getMovieData(int *, int);
void selectionSort(int[], int);
double average(int *, int);
// variables
int surveyed;
int main()
{
cout << "This program will give the average, median, and mode of the number of movies students see in a month" << endl;
cout << "How many students were surveyed?" << endl;
cin >> surveyed;
int *array = new int[surveyed];
for (int i = 0; i < surveyed; ++i)
{
cout << "How many movies did student " << i + 1 << " see?" << endl;
cin >> array[i];
}
median(*array[surveyed], surveyed);
}
double median(int *array[], int num)
{
if (num % 2 != 0)
{
int temp = ((num + 1) / 2) - 1;
cout << "The median of the number of movies seen by the students is " << array[temp] << endl;
}
else
{
cout << "The median of the number of movies seen by the students is " << array[(num / 2) - 1] << " and " << array[num / 2] << endl;
}
}
Problems:
The expression *array[surveyed] used in the following line:
median(*array[surveyed], surveyed);
is not right. array[surveyed] is the surveyed-th element of the array. It is not a pointer. It doesn't make sense to dereference it.
The type of the first argument of median used in the declaration is different than the type used in the definition. The declaration seems to be right one. Change the implementation to:
double median(int *array, int num)
Fix the way you call median. Instead of
median(*array[surveyed], surveyed);
use
median(array, surveyed);
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
C++ passing variables in from one Function to the Next.
The Program is working but when it comes to getUserData it asks for the same information 4 times and then displays the results with negative numbers. I used test numbers for number of rooms 1, 110 for sqrt feet in the room, 15.00 for cost of paint.
//Problems with this not working
void showMenu();
void getUserData(int &, double &, int &);
void doEstimate(int &, double &, int &, double &, double &);
void showReport();
int main()
{
int choice;
//I am not sure why I have to do this but someone suggested to do it and the program complied when I did this int calc ect
int calcGallonsOfPaint, rooms, totalsqrtfeet;
double calcCostOfPaint, costOfPaint;
int calcHoursOfLabor;
double calcLaborCost;
double calcPaintJobCost;
// Set up numeric output formatting.
cout << fixed << showpoint << setprecision(2);
do
{
// Display the menu and get the user's choice.
showMenu();
cin >> choice;
// Validate the menu selection.
while (choice < 1 || choice > 2)
{
cout << "Please enter 1 or 2: ";
cin >> choice;
}
if (choice == 1)
{
//for some reason it just keeps repeating the function getUserData
getUserData(rooms, costOfPaint, totalsqrtfeet);
doEstimate(calcGallonsOfPaint, calcCostOfPaint, calcHoursOfLabor, calcLaborCost, calcPaintJobCost);
showReport();
}
} while (choice != 2);
return 0;
}
void getUserData(int &rooms, double &costOfPaint, int &totalsqrtfeet)
{
int sqrtfeet;
int count = 0;
cout << "Please enter the number of rooms to be painted: ";
cin >> rooms;
cout << "Please enter square feet of wall space in each room: ";
cin >> sqrtfeet;
for (count = 1; count <= rooms; count++)
{
cout << "Please eneter square feet of wall space in room " << count << ": ";
cin >> sqrtfeet;
totalsqrtfeet += sqrtfeet;
}
cout << "What is the cost of the paint: ";
cin >> costOfPaint;
system("cls");
system("pause");
}
void doEstimate(int &calcGallonsOfPaint, double &calcCostOfPaint, int &calcHoursOfLabor, double &calcLaborCost, double &calcPaintJobCost)
{
//I am not sure why I have to do this but someone suggested to do it and the program complied when I did this: puting int rooms ect
int rooms, totalsqrtfeet;
double costOfPaint;
getUserData(rooms, costOfPaint, totalsqrtfeet);
calcGallonsOfPaint = 1 * (totalsqrtfeet/110); //Calculates the number of whole gallons of paint required.
calcCostOfPaint = calcGallonsOfPaint * costOfPaint; //Calculates the cost of the paint required.
calcHoursOfLabor = calcGallonsOfPaint * 6; //Calculates the number of whole hours of labor required.
calcLaborCost = calcHoursOfLabor * 15.00; //Calculates the labor charges.
//Calculates the cost of the paint job. This is the sum of the labor charges and the cost of the paint required.
calcPaintJobCost = calcLaborCost + calcCostOfPaint;
/*110 square feet of wall space
one gallon of paint
six hours of labor
$15.00 per hour for labor
*/
}
void showReport()
{
//I am not sure why I have to do this but someone suggested to do it and the program complied when I did this
int calcGallonsOfPaint, rooms, totalsqrtfeet;
double calcCostOfPaint, costOfPaint;
int calcHoursOfLabor;
double calcLaborCost;
double calcPaintJobCost;
getUserData(rooms, costOfPaint, totalsqrtfeet);
doEstimate(calcGallonsOfPaint, calcCostOfPaint, calcHoursOfLabor, calcLaborCost, calcPaintJobCost);
cout << "The number of rooms to be painted: " << rooms << endl;
cout << "The number of whole gallons of paint required: " << calcGallonsOfPaint << endl;
cout << "The hours of labor required: " << calcHoursOfLabor << endl;
cout << "The cost of the paint: " << calcCostOfPaint << endl;
cout << "The labor charges: " << calcLaborCost << endl;
cout << "The total cost of the paint job: " << calcPaintJobCost << endl;
system("pause");
system("cls");
}
One thing that you should do is initialise totalsqrtfeet to zero in your main function. That's because you're just adding the size of each room to it and it starts out with a random value: junk + a + b + c + d is still junk :-)
On top of that, you call getUserData from your main function and then again from doEstimate. And then you call them both again in showReport. That's why it's asking four times. Just call getUserData once. Since it's homework, I'll leave you to figure out where but here's a hint. If you do it in main (nudge, nudge, wink, wink), you'll have to pass he variables into doEstimate as well, not create new variables of the same name within that function and magically expect the compiler to associate them with the originals.
To caveat on what paxdiablo said, you are calling getUserData in your nested while loop, but I don't understand the purpose of calling getUserData(rooms, costOfPaint, totalsqrtfeet); prior to doEstimate(...) when the data isn't used nor passed to doEstimate(...) until you call getUserData again while inside the doEstimate(...) function. You should pass by value the rooms, costOfPaint, and totalsqrtfeet variables to doEstimate(...) or make them global since you only have one main() function anyways. If you had some sort of OO solution, then I wouldn't recommend making them global and rather part of a class.
Also all these variables are ZERO or NULL when they are passed into doEstimate(...):
calcGallonsOfPaint, calcCostOfPaint, calcHoursOfLabor, calcLaborCost, calcPaintJobCost
If you want to output them, then you need to pass them by reference to doEstimate(...) and then when it gets to the cout then it will sufficiently print the correct values. That is why it is zero.
The bottom line is though you need one function to call the other functions. That would be the simplest plan at this point, such as:
GetDataAndPrint(...) {
// Get some data
// Do estimate, pass in values by reference
// Print Results from calculated values
// return
}