I'm having some problems with my program which I do not understand.
On line 72, I get the error: "error C4700: uninitialized local variable 'sumInEuros' used" however surely it is initialized as I am using it to store a calculation?
Also on line 66 I get "error C4716: 'showPriceInEuros': must return a value" - why must this return a value? the function is simply meant to output a message to the console.
I'm using VS13 and it's c++.
Any help would be very much appreciated, because I am stuck!
Thanks!
#include <iostream> //for cin >> and cout <<
#include <cassert> //for assert
#include <iomanip> //for endl
#include <Windows.h>
using namespace std;
void processAPrice();
int getPriceInPounds();
int convertPriceIntoEuros(int pounds);
int showPriceInEuros(int pounds, int euros);
int calculateSum(int euros);
void produceFinalData(int sum, int numberOfPrices);
int main()
{
char answer('Y');
int numberOfPrices(0);
while (answer = 'Y')
{
processAPrice();
numberOfPrices++;
cout << "Continue? (Y/N)";
cin >> answer;
}
if (numberOfPrices > 0)
//produceFinalData(sum, numberOfPrices);
system("PAUSE"); //hold the screen until a key is pressed
return(0);
}
void processAPrice() //
{
int pounds = getPriceInPounds();
int euros = convertPriceIntoEuros(pounds);
int sum = showPriceInEuros(pounds, euros);
calculateSum(euros);
}
int getPriceInPounds() //
{
int priceInPounds;
cout << "Enter a price (in Pounds): /234";
cin >> priceInPounds;
return priceInPounds;
}
int convertPriceIntoEuros(int priceInPounds) //
{
const int conversionRate(0.82);
return priceInPounds / conversionRate;
}
int showPriceInEuros(int pounds, int euros) //
{
SetConsoleOutputCP(1252);
cout << "The Euro value of /234" << pounds << "is: \u20AC" << euros;
}
int calculateSum(int euros) //
{
int sumInEuros;
sumInEuros = (sumInEuros + euros);
return sumInEuros;
}
void produceFinalData(int sum, int numberOfPrices) //
{
SetConsoleOutputCP(1252);
cout << "The total sum is: \u20AC" << sum;
cout << "The average is: \u20AC" << (sum/numberOfPrices);
}
Well, the showPriceInEuros function is not returning the int it promises to return in its signature. That's the error.
If the function is not supposed to return a value, you should declare its return type as void:
void showPriceInEuros(int pounds, int euros);
//^^
and then:
void showPriceInEuros(int pounds, int euros) {
SetConsoleOutputCP(1252);
cout << "The Euro value of /234" << pounds << "is: \u20AC" << euros;
}
of course.
surely it is initialized as I am using it to store a calculation?
The calculation is based on the variable's uninitialised value:
sumInEuros = (sumInEuros + euros);
^^^^^^^^^^ not initialised
Perhaps you could declare it static, so that its value is preserved between calls to the function, in order to calculate the sum of all the values you pass to the function. Usually, it would be better to use a class to manage persistent data like this, with member functions to update and access it.
why must this return a value?
Because you say it does:
int showPriceInEuros(int pounds, int euros)
^^^
If it shouldn't return a value, change the return type to void.
You do not initialize sumInEuros in this function. You store a result in it - that's true but to calculate the result you are using the uninitialized value.
int calculateSum(int euros) //
{
int sumInEuros;
sumInEuros = (sumInEuros + euros);
return sumInEuros;
}
Answering the question from below:
I would probably create a class PriceCalculator which has all the functions of your algorithm plus the internal state:
class PriceCalculator {
int m_sumInEuros;
public:
PriceCalculator()
: m_sumInEuros(0) { }
void processAPrice(int price);
int getSumInEuros() const { return m_sumInEuros; }
private:
void updateSum(int priceInEuros);
};
From your main function you should create an object of this type and give it the prices you want to sum. Do not do any console input from your class.
int main()
{
PriceCalculator calc;
char answer('Y');
int numberOfPrices(0);
while (answer = 'Y')
{
int priceInPounds;
cout << "Enter a price (in Pounds): /234";
cin >> priceInPounds;
calc.processAPrice(priceInPounds);
numberOfPrices++;
cout << "Continue? (Y/N)";
cin >> answer;
}
...
You might want to think about adding the numberOfPrices to your calculator class as well. At the end you will do all the operations in your class but the user input and console output outside your class. Your class can be tested automatically this way and is completely independent from the user interface.
Related
I would like to know why does my double function returns as an integer instead of a decimal. I gave a value of 0.01 to my ic4 to go into the function and expect a return of 0.384615 but instead i get a return of 1.
#include <iostream>
#include <string>
#include <cmath>
#include <math.h>
using namespace std;
double vt = 0.026;
double ic4;
double gm7(double IC7);
int main ()
{
while(true)
{
printf("ao (in dB): ");
cin >> ao;
if (ao >= 80)
{
printf("IC7 (in Amps): ");
cin >> ic7;
cout << "IC7: " << ic7 << endl;
gm7(ic7);
cout <<"gm7: " << gm7 << endl;
}
else
{
printf("Choose another ao!\n");
}
}
}
double gm7 (double IC7)
{
return IC7 / vt;
}
gm7 is a function. You are inserting a function into the character stream.
Character streams do no have an insertion operator overloads for functions. However, they do have an overload for bool and function pointers implicitly convert to bool and function implicitly converts to a function pointer. Since the function pointer is not null, it converts to true. true is printed as 1.
P.S. The example program is ill-formed because it uses undeclared names.
just to clarify the comments
you should do this
int main ()
{
while(true)
{
printf("ao (in dB): ");
cin >> ao;
if (ao >= 80)
{
printf("IC7 (in Amps): ");
cin >> ic7;
cout << "IC7: " << ic7 << endl;
double gm7res = gm7(ic7); <======
cout <<"gm7: " << gm7res << endl; <<======
}
else
{
printf("Choose another ao!\n");
}
}
}
note you also need to declare a0
#include "assert.h"; // for some reason assert wouldn't work on my compiler without this
#include <iostream>
#include <string>
#include <limits> // This is helpful for inputting values. Otherwise, funny stuff happens
using namespace std;
class Product
{
public:
Product();
Product(string the_name, int the_price, int number_of);
string return_name();
void reduce_amount();
void print_data() const;
private:
string prod_name; // name of your product
int price_in_cents; // it's price in cents
int amount; // the number of the product that you have
};
Product::Product()
{
prod_name = "NULL_NAME: NEED DATA";
price_in_cents = 0;
}
Product::Product(string the_name, int the_price, int number_of)
{
assert(the_price>0);
assert(number_of>0);
assert(number_of<21);
assert(prod_name !="NULL_NAME: NEED DATA");
prod_name = the_name;
price_in_cents = the_price;
amount = number_of;
}
void Product::print_data() const
{
cout<<prod_name << endl;
cout<<"The price in cents is: " <<price_in_cents<< endl;
cout<< "Amount left: " << " " << amount << endl;
}
void Product::reduce_amount()
{
amount = amount -1;
}
string Product::return_name()
{
return prod_name;
}
class Vending_Machine
{
public:
Vending_Machine();
void empty_coins();
void print_vend_stats();
void add_product();
Product buy_product();
private:
int income_in_cents;
Product product1();
Product product2();
Product product3();
Product product4();
Product product5();
};
void Vending_Machine::empty_coins()
{
cout << "The total amount of money earned today is " << income_in_cents << " cents" << endl;
income_in_cents = 0;
cout << "All the coins have been withdrawn. The balance is now zero." << endl;
}
void Vending_Machine::print_vend_stats()
{
cout<< "Total income thus far: " << income_in_cents << endl;
if (product1().return_name() != "NULL_NAME: NEED DATA")
{
//stuff happens
}
}
int main()
{
return 0;
}
So, I'm not sure if I did all the identation correctly, but I'm having a problem with the boolean statement in vending machine print_vend_stats() function. It's saying I am making an undefined fereence to product1(). What does this mean?
When you declare
Product product1();
you declare a member function, the parentheses is what makes it a function.
If you drop the parentheses
Product product1;
you declare a member variable, an actual instance of the Product class.
Another example, you wouldn't write e.g.
int income_in_cents();
do declare income_in_cents as a variable, now would you?
It doesn't matter if the type is a primitive type like int, or a class like Product, Member variables are declared like normal variables like you do anywhere else.
I've started a project in C++ to practice the use of parameters and I have encountered a problem in my code and I'm not quite sure why I'm getting the values I'm getting.
Here is my code:
When I run it, the values I receive from the displayFinalData output as 0 instead of the values I'm expecting (which should be whatever the conversion is etc).
#include <iostream>
using namespace std;
int main()
{
int numInEuros = 0;
char answer = 'Y';
double sumEuro = 0;
double priceEuro = 0;
int number = 0;
while ((answer == 'Y') || (answer == 'y'))
{
void processAPrice();
processAPrice();
void calculateSum(double priceInEuros, double& sumInEuros);
calculateSum(priceEuro, sumEuro);
cout << "\nDo you wish to continue? (Y/N): ";
cin >> answer;
number += 1;
}
void displayFinalData(double sumInEuros, int number);
displayFinalData(sumEuro, number);
system("pause");
return 0;
}
void processAPrice()
{
double pricePounds;
double priceEuro;
void getPriceInPounds(double& priceInPounds);
getPriceInPounds(pricePounds);
void convertPriceIntoEuros(double priceInPounds, double& priceInEuros);
convertPriceIntoEuros(pricePounds, priceEuro);
void showPriceInEuros(double priceInPounds, double priceInEuros);
showPriceInEuros(pricePounds, priceEuro);
}
void getPriceInPounds(double& priceInPounds)
{
cout << ("\nEnter price in pounds: \x9C");
cin >> priceInPounds;
}
void convertPriceIntoEuros(double priceInPounds, double& priceInEuros)
{
double conversionRate = 0.82;
priceInEuros = (priceInPounds / conversionRate);
}
void showPriceInEuros(double priceInPounds, double priceInEuros)
{
cout << ("\nThe Euro value of \x9C") << priceInPounds << " is EUR " << priceInEuros << "\n";
}
void calculateSum(double priceInEuros, double& sumInEuros)
{
sumInEuros += priceInEuros;
}
void displayFinalData(double sumInEuro, int number)
{
cout << "\nThe total sum is: EUR " << sumInEuro << "\n";
cout << "\nThe average is: EUR " << (sumInEuro / number) << "\n\n";
}
You declared priceEuros variable separately in your processAPrice() function and that gets updated after user inputs price in pounds, but the priceEuro variable in main() is untouched, and keeps incrementing your sumEuro by 0.
If you pass your priceEuros variable in main to the processAPrice() function it would work
void processAPrice(double& priceInEuros)
{
double pricePounds;
void getPriceInPounds(double& priceInPounds);
getPriceInPounds(pricePounds);
void convertPriceIntoEuros(double priceInPounds, double& priceInEuros);
convertPriceIntoEuros(pricePounds, priceInEuros);
void showPriceInEuros(double priceInPounds, double priceInEuros);
showPriceInEuros(pricePounds, priceInEuros);
}
I'm guessing you want to update the priceEuros variable? The problems is that it's a local variable. Local variables in different function have no relation, even if the have the same symbolic names.
For variables you want to share between functions you need to make them global, i.e. declare them outside the scope of any function.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
//Long story short, trying to do a media library, but I am at a 100% Complete loss on why I cannot get this data to work. This is my Main.cpp
#include "CDclass.h"
bool fills = true;//Public Switch to turn on/off autofill of "Data" classes.
bool runner = true;//Public switch that helps with the program functionality(DO NOT EDIT)
void main()
{
int decision;
unsigned int total = 5;
vector<string> titles;
vector<double> time;
string artist;
string name;
titles.resize(total);
time.resize(total);
vector<cdStorage> Data;//A vector of classes
cdStorage newCD;
Data.push_back(newCD);
Data.push_back(newCD);
Data.push_back(newCD);//This was used as a sizing test and it works.
cdStorage::cdStorage(total);
//I used this to loop without restarting main.
while(runner == true)
{
if(fills == true)//Autofill to get the program running
{
artist = "Bunny";
name = "Bread";
for(unsigned int x = 0; x < Data.size(); x++)
{
cdStorage::cdStorage(total);
Data[x].setNewArtist(artist);
Data[x].setNewName(name);
for(unsigned int y = 0; y < total; y++)
{
titles[y] = "TestfieldBanana!";
time[y] = 12.13;
Data[x].setNewTitles(y, titles[y]);
Data[x].setNewTime(y, time[y]);
}
}
fills = false;
}
cout << Data[0].getNewArtist() << endl;
cout << "*******************" << endl <<
"*Media Awesomsauce*" << endl <<
"*******************" << "\n\n" <<
"********************" << endl <<
"* 1: Check Library *" << endl <<
"* 2: Add CD *" << endl <<
"* 3: Delete CD *" << endl <<
"* 4: Exit Program *" << endl <<
"********************" << "\n\n" <<
"Decision:_";
cin >> decision;
//The majority of all of this is very self explanatory.
if(decision == 1)
{
for(unsigned int x = 0; x < Data.size(); x++)
{
cdStorage::cdStorage(total);
cout << Data[x].getNewName() << "\t";
cout << Data[x].getNewArtist() << "\t";
for(unsigned int y = 0; y < total; y++)
{
//int length = Data[x].getNewName().length();
cout << "\t\t\t" << Data[x].getNewTitles(y);
cout << "\t" << Data[x].getNewTime(y) << endl;
}
}
}else if(decision == 2)
{
Data.push_back(newCD);
system("CLS");
cout << "What is the name of the CD: ";
cin >> name;
cout << "\nWhat is the name of the Artist: ";
cin >> artist;
cout << "\nHow many songs are there: ";
cin >> total;
cdStorage::cdStorage(total);
titles.resize(total);
time.resize(total);
Data[Data.size()].setNewName(name);
Data[Data.size()].setNewArtist(artist);
cout << "What are the song titles and lengths:\n";
for(unsigned int x = 0; x < total; x++)
{
cout << "Title " << x+1 << ": ";
getline (cin, titles[x]);
cout << "Length(Example: 3.36 for 3 mins and 36 seconds): ";
cin >> time[x];
cout << endl;
Data[Data.size()].setNewTitles(x, titles[x]);
Data[Data.size()].setNewTime(x, time[x]);
}
}else if(decision == 3)
{
}else if(decision == 4)
{
runner = false;
}else
{
system("CLS");
cout << "Error: You must choose a number between 1-5...\n\n";
system("pause");
system("CLS");
}
}
}
//This is my CDWorks.cpp
#include "CDclass.h"
//Constructor
cdStorage::cdStorage(){};
//Overloaded Constructor
cdStorage::cdStorage(unsigned int theTotal)
{
newTotal = theTotal;
newTitles.resize(newTotal);
newTime.resize(newTotal);
}
//Accessors
unsigned int cdStorage::getNewTotal() const
{
return newTotal;
}
string cdStorage::getNewTitles(unsigned int x) const
{
return newTitles[x];
}
double cdStorage::getNewTime(unsigned int x) const
{
return newTime[x];
}
string cdStorage::getNewArtist() const
{
return newArtist;
}
string cdStorage::getNewName() const
{
return newName;
}
//Mutators
void cdStorage::setNewTotal(unsigned int theTotal)
{
newTotal = theTotal;
}
void cdStorage::setNewTitles(unsigned int x, string theTitle)
{
newTitles[x] = theTitle;
}
void cdStorage::setNewTime(unsigned int x, double theTime)
{
newTime[x] = theTime;
}
void cdStorage::setNewArtist(string theArtist)
{
newArtist = theArtist;
}
void cdStorage::setNewName(string theName)
{
newName = theName;
}
//Destructor
cdStorage::~cdStorage(){}
//This is my CDClass.h
#include <iostream>
#include <string>
#include <vector>
using namespace std;
#ifndef CDCLASS_H
#define CDCLASS_H
class cdStorage
{
private:
unsigned int newTotal;
vector<string> newTitles;
vector<double> newTime;
string newArtist;
string newName;
public:
//Constructor
cdStorage();
//Overloaded Constructor
cdStorage(unsigned int);
//Destructor
~cdStorage();
//Accessors
unsigned int getNewTotal() const;
string getNewTitles(unsigned int) const;//The integer is to track which element needs returned.
double getNewTime(unsigned int) const;
string getNewArtist() const;
string getNewName() const;
//Mutators
void setNewTotal(unsigned int);
void setNewTitles(unsigned int, string);
void setNewTime(unsigned int, double);
void setNewArtist(string);
void setNewName(string);
};
#endif
Data[Data.size()] is accessing outside the vector Data, which is undefined behaviour, so anything can happen.
Also, I don't know what you think repeatedly calling cdStorage::cdStorage(total); does, but it doesn't do anything except create a new (anonymous) object that is immediately thrown away.
All the cdStorages you have created were created using the default (parameterless) constructor, which leaves newTotal totally uninitialized, and the vectors are both empty. You can't modify them by calling a constructor afterwards (I suspect that is what yo're trying to accomplish).
Since the vectors are empty, when you say e.g. newTitles[x] = theTitle;, you're accessing invalid memory, which means that your program, again, has undefined behaviour.
It's very difficult to say whether these are the cause of your problems, but you should probably fix them first before you go on.
You should probably review the chapter on constructors and instance creation in your Fine Book.
Data[Data.size()].setNewName(name);
This accesses past the end of the vector, it only has Data.size() elements, starting from zero. This is undefined behaviour and probably causing the problem.
It may not be the problem, but as you haven't said where the error happens it's hard to know. You have the failing program, you should be able to debug it and say where it blows up ... you've had three days to learn to use a debugger!
Until you know what you're doing I suggest you stop using [x] to access vectors and switch to using the at(x) function, which does the same thing but checks that x is a valid index and not larger than the vector's size. If you'd done that then you'd have got an exception at the first problem, instead of undefined behaviour and a stack overflow.
There are a number of other issues...
Put your include guards at the top of the file, not after other headers.
Never put using namespace at namespace scope in a header.
You keep doing this:
cdStorage::cdStorage(total);
What's that supposed to do and why do you keep doing it?
You should use member initializers in constructors instead of altering them in the constructor body:
cdStorage::cdStorage(unsigned int theTotal)
{
newTotal = theTotal;
newTitles.resize(newTotal);
newTime.resize(newTotal);
}
i.e. do this instead:
cdStorage::cdStorage(unsigned int theTotal)
: newTotal(theTotal), newTitles(theTotal), newTime(theTotal)
{ }
I got a program to create in C++ in our introduction to C++ class in school. I am doing everything as I got in examples, but still getting errors.
w4x.cpp was given and I have to create Molecule.h and Molecule.cpp. I did that, but I am getting errors because my variables were not declared in scope, but I can't understand why.
// w4x.cpp
#include <iostream>
using namespace std;
#include "w4x.h"
#include "Molecule.h"
int main() {
int n = MAX_MOLECULES;
Molecule molecule[MAX_MOLECULES];
cout << "Molecular Information\n";
cout << "=====================" << endl;
for (int i = 0; i < MAX_MOLECULES; i++) {
if (!molecule[i].read()) {
n = i;
i = MAX_MOLECULES;
}
cout << endl;
}
cout << "Structure Name Mass\n";
cout << "==================================================" << endl;
for (int i = 0; i < n; i++)
molecule[i].display();
}
//Molecule.h
const int MAX_STRUCT = 10;
const int MAX_NAME = 20;
class Molecule {
char name[MAX_STRUCT];
char rate[MAX_NAME];
double weight;
public:
Molecule();
void read(const char*, const char*, double);
void display() const;
~Molecule();
};
//Molecule.cpp
#include <iostream>
#include <cstring>
using namespace std;
#include "Molecule.h"
Molecule::Molecule(){
name[0]= '\0';
rate[0]= '\0';
weight = 0;
}
void::read(const char* n, const char* r, double w) {
weight = w;
strncpy (name, n, MAX_STRUCT);
name[MAX_STRUCT]='\0';
strncpy (rate, r, MAX_NAME);
rate[MAX_NAME]='\0';
cout << "Enter structure : ";
cin.getline (n, MAX_CHARS);
cout << "Enter full name : ";
cin.getline (r, MAX_NAME);
cout << "Enter weight : ";
cin >> w;
}
void::display() const
{
int x;
for ( x=0; x<i; x++)
cout << n << " " << r << " " << w << endl;
}
My first question is, how can I pass char name[MAX_STRUCT]; char rate[MAX_NAME]; double weight; from Molecule.h to Molecule.cpp
The problem with your definitions is here:
void::read(const char* n, const char* r, double w)
and here
void::display() const
What :: says here, is that you are implementing a function within a class. So you need to specify which class and which function! What you are telling it now, is that you are implementing a function inside class void, which is nonexistent.
You should convert them to:
void Molecule::read(const char* n, const char* r, double w)
void Molecule::display() const
Your other question regarding passing class members:
The functions of a class have access to its variables, therefore, you don't need to concern yourself with that. Just use the variables.
Also, if you notice in your w4x.cpp, the function Molecule::read() is called without parameters, so your TAs ask you to implement it without parameters. Indeed, since you have access to Molecule::name, Molecule::rate and Molecule::weight directly, you should read data and write to those variables instead of asking for parameters. Therefore, your read function would look like this:
void Molecule::read()
{
// read into name, rate and weight
}
Furthermore, w4x.cpp expects read to report whether it has been successful or not. This means that you should do error checking in Molecule::read and return 0 if no errors or -1 (for example) in case of errors.