I am a newbie at C++, and I am trying to make a "calculator" which: adds two numbers, subtracts two numbers, multiplies two numbers, divides two numbers, takes the sine of a number, takes the cosine of a number, or takes the tangent of a number. Here is the code:
#include <iostream>;
#include <cmath>;
#include <string>
int main ()
{}
int ask(std::string operation);
{
std::cout<<"Type Addition, Subtraction, Multiplication, Division, Sine, Cosine, or Tangent:\n";
std::cin>>operation;
if (operation="Addition")
{
goto Add
}
float Add(float addend1, float addend2, float answer)
{
Add:
std::cout<<"Insert the first number to be added:\n";
std::cin>>addend1;
std::cout << "Insert the second number to be added:\n";
std::cin>>addend2;
answer=addend1+addend2;
std::cout<<addend1<<"+"<<addend2<<"="<<answer<<"\n";
break
}
}
There will be more functions later, but my problem is on line 7. There is an error that says: expected unqualified-id before "{" token. I know my indentation is horrible, but thanks!
You have a lot of issues in your code.
First, as Ivan points out, you are trying to define a function inside of a function (ask() inside main()). That isn't valid.
Second, you have a goto (why?!) attempting to jump to a label in another function. I doubt your compiler will even allow that, but how would you expect that to work? You are attempting to use variables passed to your function addition that don't exist as you never call the function and the stack has never been setup for it. This is bad, don't do it, just call the function properly.
Third, the #include preprocessor directive is terminated with a newline, not a semicolon. That could cause some (relatively) hard to track down compilation errors.
Fourth, you are mistakenly attempting to assign the const char* "Addition" to operation when what you meant to use was the equality operator ==. That won't work ether though because operation is an r-value and cannot be assigned to like that. If you want to modify it you will need to declare it as a pointer, but once again, that's not what you are going for semantically...
If you want to compare strings and (for whatever reason...) are intent on using pointers to char then you should be using strcmp. That said, you are in C++ land, so just use std:string instead.
Try something like this. I haven't enhanced your code in anyway, just made it something that will compile and run. I have made a few changes.
Aside from getting rid of a few syntax errors, your original Add function took the result as a float argument. Assigning to that from within the function would only modify a copy. You would need to take a pointer or reference if you want the caller to see the modified value, but you don't need that at all as you can simply return the result.
The string comparison is case sensitive, so you would probably want to change it to be case insensitive. I'm assuming no localization here :). I'm not performing error checking on the input either, so be aware that it may fail if the user enters something other than a valid floating point number.
#include <iostream>
#include <string>
using namespace std;
void Ask();
float Add( float, float );
int main( size_t argc, char* argv[] )
{
Ask();
return 0;
}
void Ask()
{
cout << "Type Addition, Subtraction, Multiplication, Division, Sine, Cosine, or Tangent:\n";
string operation;
cin >> operation;
if( operation == "Addition" )
{
float first = 0, second = 0;
cout << "enter first operand";
cin >> first;
cout << "enter second operand";
cin >> second;
cout << "The result is: " << Add( first, second );
}
}
float Add( float first, float second )
{
return first + second;
}
С++ doesn't allow nested functions. You have function main() and trying to declare function ask() inside it. And compiler doesn't know what you want.
I commented your code a little bit, maybe that gets you started:
#include <iostream>;
#include <cmath>;
#include <string>;
int main () {
int ask (){ //you cannot nest functions in C++
char operation [20]; //why not use the string class if you include it anyway
std::cout<<"Type Addition, Subtraction, Multiplication, Division, Sine, Cosine, or Tangent:\n";
std:cin>>operation;
if (operation="Addition"){ //you cannot compare char-strings in C++ like that
goto Addition; //don't use goto (I don't want to say "ever", but goto is only used in extremely rare cases) make a function call instead
}
}
float addition(float addend1, float addend2, float answer) //you probably want to declare the variables inside the function
{
Addition: //don't use labels
std::cout<<"Insert the first number to be added:\n";
std::cin>>addend1;
std::cout << "Insert the second number to be added:\n";
std::cin>>addend2;
answer=addend1+addend2;
std::cout<<addend1<<"+"<<addend2<<"="<<answer<<"\n";
}
Let's try to break this down..
You shouldn't use ; on the precompiler directives.
#include <iostream>;
#include <cmath>;
#include <string>;
Should be
#include <iostream>
#include <cmath>
#include <string>
.
int main () {
int ask (){
See Ivans answer for this
char operation [20];
std::cout<<"Type Addition, Subtraction, Multiplication, Division, Sine, Cosine, or Tangent:\n";
std:cin>>operation;
if (operation="Addition"){
You can use std::string instead which is alot easier to deal with. Then you can write
#include <string>
...
std::cout<<"Type Addition, Subtraction, Multiplication, Division, Sine, Cosine, or Tangent:\n";
std::string myString;
getline(cin, myString);
if (myString == "Addition"){
.
goto Addition;
}
}
float addition(float addend1, float addend2, float answer)
{
Not sure what is going on here.. but let's break Addition to it's own function
void Addition(){
// do addition here
}
.
Addition:
std::cout<<"Insert the first number to be added:\n";
std::cin>>addend1;
std::cout << "Insert the second number to be added:\n";
std::cin>>addend2;
answer=addend1+addend2;
std::cout<<addend1<<"+"<<addend2<<"="<<answer<<"\n";
}
Don't forget that you have to define the variables
int addend1;
int addend2;
int answer;
Hope this helps you along the way.
First int ask() what is that.Why do you start a block here.
Second you have two {s and three }s that's because of the ask().
I think that c++ does not support anonymus functions.
Third why do you use goto,when you have a function,just call the function.
Fourh your addition func should either be void or remove it's last parameter.
Also I think that you don't need string.h file unless you use some rather advanced funcs,the char array should be enough for your program.
Related
I have write this code to solve a quadratic formula but it doesn't work when the answer is complex(in iota form like 3i or √-3) i want to get answer in iota how could i manage it
#include<iostream>
#include<math.h>
using namespace std;
int main(){
float a,b,c,variable1,variable2,variable3,y,x,variable4;
cout<<"Enter a:";
cin>>a;
cout<<"Enter b:";
cin>>b;
cout<<"Enter c:";
cin>>c;
variable1=-b;
variable2=b*b;
variable3=(4*a*c);
variable4=(variable2-variable3);
y=sqrtf(variable4);
x=(variable1+y)/2;
cout<<"x=" <<x <<endl;
}
The overload of std::sqrt that produces a complex result is declared in <complex> and takes a std::complex<T> as its argument, so to get a complex result, you need to start with a complex input, and include the correct header.
Here's a trivial example:
#include <complex>
#include <iostream>
int main() {
std::complex<double> d{ -1, 0 };
std::cout << std::sqrt(d);
}
Result:
(0,1)
Those represent the real and imaginary parts respectively, so this is 0+1i, as we'd expect.
It may also be worth noting that starting with C++ 14, the standard library defines a user-defined literal for imaginary numbers, so you could initialize d like this:
using namespace std::literals;
auto d = -1.0 + 0i;
This produces the same result, but for people accustomed to writing a complex number as a + bi, it may look a little more familiar/comfortable. The one "trick" is that it's still doing type deduction, so to get a complex<double>, you need to use -1.0 instead of -1 (which I guess would try to deduce a std::complex<int>).
I've written a simple series of functions. When I try to call the last function I get the "linker command" error. The syntax is correct but my program won't compile. Am I missing something or is this an IDE issue?
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <time.h>
using namespace std;
// Function Prototypes
int numGen ();
int questSol ();
int questAns ();
int main() {
// Store values of functions in variables
int ans = questAns();
int sol = questSol();
if (ans == sol){
cout << "Very good! Press Y to continue" << endl;
questAns();
} else {
cout << "Incorrect. Please try again" << endl;
cin >> ans;
if(ans == sol){
questAns();
}
}
return 0;
};
//Generates two random numbers between zero and ten and returns those numbers
int numGen () {
srand(time(0));
int one = rand() % 10;
int two = rand() % 10;
return one;
return two;
};
//Takes in the random numbers, multiplies them, and returns that result
int questSol (int one, int two) {
int solution = one * two;
return solution;
}
//Takes in random numbers, displays them in cout statement as question, receives and returns user answer to
//question
int questAns (int one, int two) {
int answer;
cout << "How much is " << one << " times " << two << "? \n";
cin >> answer;
return answer;
}
You forward declare a function:
int questAns ();
And then later define a function with a signature:
int questAns (int one, int two);
In C++, functions can have the same name but have different parameters (overloaded functions), so you've never actually defined the questAns that you forward declare and then try to call.
Note: You have the same problem with questSol.
It looks like you don't quite understand the scope of local variables.
Inside numGen you define two ints, one and two. Variables defined within a block (curly braces: {}) exist only within that block. They are local to it. The identifier is only valid within the inner-most block it's defined in, and once you exit it that memory is freed. Returning two ints like you're trying is also impossible.
It looks like you're expecting those ints to be available to your other two functions.
The smallest change you could make is to make int one and two global variables. This means you define them outside of any block (usually at the very top of your code). Then remove the parameter lists from your function definitions, because all the functions can see the global variables. That's generally considered bad programming practice because in more complex programs globals wreak havoc on your code, but in this simple program it'd work and give you a chance to practice understanding variable scope.
Another solution, more in line with what you were trying, is to define an ARRAY of two ints, and return that. Then pass that array to the other two functions. That'd be a better way to do it, and give you a chance to learn about arrays.
You have several problems:
numGen - You cannot return two separate values this way
// Function Prototypes
int numGen ();
int questSol ();
int questAns ();
Says that you have 3 functions all of which return an int and are called with no parameters - which is how you call them.
So the linker is looking for functions with a fingerprint of int_questSol_void and int_questAns_void - you then declare two functions that return an int and take as inputs 3 ints - these have fingerprints of int_questAns_int_int and int_questSol_int_int.
As a result the linker is moaning that you are calling to functions that it can't find.
If I prototype a function above the main function in my code, do I have to include all parameters which have to be given? Is there a way how I can just prototype only the function, to save time, space and memory?
Here is the code where I came up with this question:
#include <iostream>
using namespace std;
int allesinsekunden(int, int, int);
int main(){
int stunden, minuten, sekunden;
cout << "Stunden? \n";
cin >> stunden;
cout << "Minuten? \n";
cin >> minuten;
cout << "Sekunden= \n";
cin >> sekunden;
cout << "Alles in Sekunden= " << allesinsekunden(stunden, minuten, sekunden) << endl;
}
int allesinsekunden (int h, int m, int s) {
int sec;
sec=h*3600 + m*60 + s;
return sec;
}
"If I prototype a function above the main function in my code, do I have to include all parameters which have to be given?"
Yes, otherwise the compiler doesn't know how your function is allowed to be called.
Functions can be overloaded in c++, which means functions with the same name may have different number and type of parameters. Such the name alone isn't distinct enough.
"Is there a way how I can just prototype only the function, to save time, space and memory?"
No. Why do you think it would save any memory?
No, because it would add ambiguity. In C++ it's perfectly possible to have two completely different functions which differ only in the number and/or type of input arguments. (Of course, in a well-written program what these functions do should be related.) So you could have
int allesinsekunden(int, int, int)
{
//...
}
and
int allesinsekunden(int, int)
{
//...
}
If you tried to 'prototype' (declare) one of these with
int allesinsekunden;
how would the compiler know which function was being declared? Specifically how would it be able to find the right definition for use in main?
You have to declare the full signature of your function, i.e. the name, the return value, all parameters with types, their constness, etc.
I'm studing structures, in the fallowing code my teacher created a structure of the complex numbers (numbers that are formed by two parts: a real one and an imaginary one).
#include <iostream>
#include <cmath>
#ifndef COMPLEX_DATA_H
#define COMPLEX_DATA_H
struct complex_data
{
double re = 0; // real part
double im = 0; // immaginary part
};
#endif
int main()
{
std::cout << "Insert two complex numbers (re, im): ";
complex_data z1, z2;
std::cin >> z1.re >> z1.im;
std::cin >> z2.re >> z2.im;
... // the code continues
}
I'd like to ask two questions:
Leaving z1 and z2 uninitialized will cause any trouble considering they're inside a function and their default inizialitation is undefined?
How can we write the actual form of a variable that is a complex number?
In reality is something like this c = 3 + 2i.
But if we write it, the computer will sum it because it don't know the difference between real numbers and imaginary ones. So we'll be forced to use a string, but in this case it'll become a sequence of charcaters! Any idea?
Using Ubuntu 14.04, g++ 4.9.2.
Since C++11, you have User defined literal (and since C++14 you have the standard literal operator ""i for the pure imaginary number of std::complex<double>).
You may write your own operator ""_i for your custom struct complex_data and also operator + to have what you expect, something like:
constexpr complex_data operator"" _i(unsigned long long d)
{ return complex_data{ 0.0, static_cast<double>(d) }; }
Live example.
Q1- Constructors are meant to intialize the member variables use them.
Q2- Actual Form can be written using strings its just matter of displaying.
c = 3 + 2i.
Compiler really dont know this, you can overload + operarator.
if you define + operator addition will be performed. (whatever code is written in that function e.g real+= a.real;)
Hi i have the below code
# include <iostream>
# include <limits>
# include <cmath>
using namespace std;
class fahrenheit
{
float f,c,x;
public:
void getdata();
void display();
}
void fahrenheit::getdata()
{
cout << "Enter the value of f : ";
cin >> f;
x=f-32;
c=5/9(x); //Here i am getting error as Expression must have (pointer-to-)function type //
}
void fahrenheit::display()
{
cout << "c=" << c;
std::cin.ignore();
std::cin.get();
}
int main()
{
fahrenheit f;
f.getdata();
f.display();
}
i have given the datatype as float for the input variables , but i am not sure what should be done to rectify the error .
5/9(x) doesn't remotely look like C++. You likely meant c = 5.0 / 9.0 * x;
first of all, you forgot about a semicolon right after the class definition.
Second, I presume you wanted to multiply x by 9. Write
c=5/9*(x)
otherwise the compiler tries to find a function called 9(int x) (which is an incorrect name for a function anyway) and realizes that 9 is in no sense any function pointer but just an int.. that's what the error means.
By the way.. if you write 5/9 compiler understands it as int values being divided.
It will divide int(5) by 9 using an int / operator, which after dividing will return
floor(5/9) = 0 . If you want to have a float or double division you have to inform the compiler that your values are floats(doubles).
For doubles: 5.0/9.0*x
For floats: 5.0f/9.0f * x
You should use the multiplication operator *.
c=5/9*(x);