I am a new C++ programmer. I am creating a calculator, and I have a problem with my void printAnswer() function. Whenever I call the function and I type in the parameter (which is a double variable), the function name always turns into a variable identifier. When I compile, it says
Severity Code Description Project File Line Suppression State
Error (active) E0070 incomplete type is not allowed Calculator C:\Users\jk\Downloads\Coding Stuff\Calculator\Calculator.cpp 17
Error C2182 'printAnswer': illegal use of type 'void' Calculator C:\Users\jk\Downloads\Coding Stuff\Calculator\Calculator.cpp 17
Warning C4244 'initializing': conversion from 'double' to 'int', possible loss of data Calculator C:\Users\jk\Downloads\Coding Stuff\Calculator\Calculator.cpp 17
This is my header file.
#ifndef CALCULATOR_H
#define CALCULATOR_H
void calculator();
double getValue1(double);
double getValue2(double);
std::string getOperation(std::string);
double calculation(double, double, std::string);
void printAnswer(double);
#endif
This is my main file
#include <iostream>
#include <string>
#include "Calculator.h"
int main()
{
double a{};
double b{};
double x{ getValue1(a) };
std::string calculatorOperation{};
std::string operation{ getOperation(calculatorOperation) };
double y{ getValue2(b) };
double answer{ calculation( x, y, operation ) };
void printAnswer(answer);
/*
* if (answer == 99999999999999999.999)
* std::cout << "Sorry. The desired operation does not exist or you have misspelled
somthing.\n";
* else
* std::cout << "The answer is " << answer << ".\n";
*
* return 0;
*/
}
double getValue1(double x)
{
std::cout << "Please type your first number and press enter.\n";
std::cin >> x;
return x;
}
double getValue2(double y)
{
std::cout << "Please type your second number and press enter.\n";
std::cin >> y;
return y;
}
std::string getOperation(std::string operation)
{
std::cout << "Please type in the desired operation in all undercase and press enter.\n";
std::cin >> operation;
return operation;
}
double calculation(double x, double y, std::string operation)
{
if (operation == "addition")
return x + y;
else if (operation == "subtraction")
return x - y;
else if (operation == "multiplication")
return x * y;
else if (operation == "division")
return x / y;
else
return 99999999999999999.999;
}
void printAnswer(double answer)
{
if (answer == 99999999999999999.999)
std::cout << "Sorry. The desired operation does not exist or you have misspelled somthing.\n";
else
std::cout << "The answer is " << answer << ".\n";
}
In your main function, you have this line:
void printAnswer(answer);
Here the compiler thinks that you are trying to declare a void variable named printAnswer which is constructed from the value answer. The compiler gives an error since you can't create a void variable.
It seems you want to call the function printAnswer with the argument answer. The correct syntax for that is:
printAnswer(answer);
Related
This question already has answers here:
Resolve build errors due to circular dependency amongst classes
(12 answers)
Closed last month.
I was trying to write some code with classes instead of structures (Some task that our proffesor gave us), The task is to convert from Cartesian to Spherical and the other way around, so dont bother with some finesses (namespace, encapsulation...) that is not accented in this very example. I encountered a very silly error that i haven't seen so far, and i am unfortunately unable to solve it..
If you pay attention you will see that there are two methods with identical names (ToMe(...)) and even parameters (The only difference is the parameter type). When i run this code with declaration of the ToMe procedure in Decard Class commented i get the desired result, but when i want to run it in this shape it says the following:
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
error C2143: syntax error: missing ',' before '&'
error C2065: 'S': undeclared identifier
Does anyone have any clue to why it keeps breaking?
#include<iostream>
#include<math.h>
using namespace std;
class Decard
{
double m_x;
double m_y;
double m_z;
public:
Decard() :m_x{0}, m_y{ 0 }, m_z{ 0 } {}
Decard(double x, double y, double z) :m_x{ x }, m_y{ y }, m_z{ z }{}
double GetX() const { return m_x; }
double GetY() const { return m_y; }
double GetZ() const { return m_z; }
void Ucitaj()
{
cout << "Unesite koordinate tacaka u dekartovom koordinatnom sistemu x,y, i z respektivno" << endl;
cin >> m_x >> m_y >> m_z;
}
void ToMe(const Spheric& S) //THIS IS THE LINE THAT MAKES PROBLEMS
{
m_x = S.GetR() * sin(S.GetTheta()) * cos(S.GetPhi());
m_y = S.GetR() * sin(S.GetTheta()) * sin(S.GetPhi());
m_z= m_x = S.GetR() * cos(S.GetTheta());
}
void Print()
{
cout << "U dekartovom :" << endl;
cout << "X:" << m_x << endl << "Y:" << m_y << endl << "Z:" << m_z << endl;
}
};
class Spheric
{
double m_r;
double m_phi;
double m_theta;
public:
Spheric() :m_r{ 0 }, m_phi{ 0 }, m_theta{ 0 } {}
Spheric(double x, double y, double z) :m_r{ x }, m_phi{ y }, m_theta{ z }{}
void Ucitaj()
{
cout << "Unesite koordinate tacaka u sfernom koordinatnom sistemu r,fi, i teta respektivno" << endl;
cin >> m_r >> m_phi >> m_theta;
}
void Print()
{
cout << "U sfernom :" << endl;
cout << "R:" << m_r << endl << "Phi:" << m_phi << endl << "Theta:" << m_theta<< endl;
}
void ToMe(const Decard& D)
{
m_r = sqrt(pow(D.GetX(), 2) + pow(D.GetY(), 2) + pow(D.GetZ(), 2));
m_phi = atan(D.GetY() / D.GetX());
m_theta = atan(D.GetZ() / m_r);
}
double GetR() const { return m_r; }
double GetPhi() const { return m_phi; }
double GetTheta() const { return m_theta; }
};
int main()
{
Decard D{ 1,2,3 };
Spheric S;
S.ToMe(D);
S.Print();
D.ToMe(S);
D.Print();
return 0;
}
What i have tried is placing the definition of the procedure outside of the class:
void Decard::ToMe(const Spheric& S)
{
.
.
.
}
And i saw something interesting, Visual Studio pointed out that the parameter type of this outplaced defenition does not match "const <error_type> &S" in the declaration of the procedure.
You need a forward declaration. Like this
class Spheric; // forward declaration
class Decard
{
...
void ToMe(const Spheric& S); // not defined yet
...
};
class Spheric
{
...
};
// now Decard::ToMe can be defined
inline void Decard::ToMe(const Spheric& S)
{
m_x = S.GetR() * sin(S.GetTheta()) * cos(S.GetPhi());
m_y = S.GetR() * sin(S.GetTheta()) * sin(S.GetPhi());
m_z= m_x = S.GetR() * cos(S.GetTheta());
}
The foeward declaration allows you to mention the class Spheric but not to use it. So the definition of Decard::ToMe must be postponed until both classes have been fully defined.
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
I wrote this code to check the exceptions I learned in a video, and now I tried to make the cube of an integer and if the entered number is not an integer I want the exception to be announced to the user.
#include <iostream>
float cube( float x)
{
char ch;
std::cin.get(ch);
if(ch=='.')
throw "Should be an integrer";
float cube=x*x*x;
return cube;
}
int main ()
{
float x;
std::cout<<" Enter an integrer : ";
std::cin>>x;
float cube_x=cube(x);
std::cout<<"Cube("<<x<<")="<<cube_x<<std::endl;
return 0;
}
You can use boost lexical-cast which is exactly for this purpose. It will throw an exception the conversion fails. Boost is well tested and you can safly use it to do the conversion for you.
This could look like this:
#include <boost/lexical_cast.hpp>
#include <iostream>
int cube(int x)
{
return x*x*x;
}
int main()
{
std::string x;
std::cout << " Enter an integrer : ";
std::cin >> x;
try
{
int y = boost::lexical_cast<int>(x);
int cube_x = cube(y);
std::cout << "Cube(" << x << ")=" << cube_x << std::endl;
}
catch (const boost::bad_lexical_cast &e)
{
std::cerr << e.what() << '\n';
}
return 0;
}
By the way, if your program shall only handle integers, you should also use type int and not float to handle the numbers.
Add the following to your source code:
#include <math.h> /* round, floor, ceil, trunc */
...
if (x == round(x)) {
...
}
Explanation can be found here: C++ Reference
Why does the following code always prints "type is double"? (I have seen this code in StackOverflow)
#include <iostream>
void show_type(...) {
std::cout << "type is not double\n";
}
void show_type(double value) {
std::cout << "type is double\n";
}
int main() {
int x = 10;
double y = 10.3;
show_type(x);
show_type(10);
show_type(10.3);
show_type(y);
return 0;
}
http://en.cppreference.com/w/cpp/language/overload_resolution says:
A standard conversion sequence is always better than a user-defined conversion sequence or an ellipsis conversion sequence.
void show_type(double value) {
std::cout << "type is double\n";
}
if u comment above line then output will be
type is not double
type is not double
type is not double
type is not double
it means that compile always prefer the void show_type(double value) over void show_type(...).
in your case if you want call the method void show_type(...) pass the two or more arguments when u calling this method show_type(firstParameter,secondParameter)
#include <iostream>
void show_type(...) {
std::cout << "type is not double\n";
}
void show_type(double value) {
std::cout << "type is double\n";
}
int main() {
int x = 10;
double y = 10.3;
show_type(x);
show_type(10);
show_type(10.3);
show_type(y);
show_type(4.0,5); //will called this method show-type(...)
return 0;
}
now the output of above line will be
type is double
type is double
type is double
type is double
type is not double //notice the output here
more info on var-args
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.