C++ Programming, Cannot understand errors - c++

I am a beginner at c++ programming, and this is only my second program. I am getting a consistent error of "expected unqualified-id before..." idk what it means and cannot solve it. This is on lines 21,27,29,33,35,38,40,43,45.48,54,56,59,61,64,66,70.
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <math.h>
using namespace std;
int main ();
int a, b, c, x,y;
int discriminant;
double x1, x2;
int countdataisinvalid=0;
int countdataisvalid=0;
int countnolastterm=0;
int countonexvalue=0;
int countnomiddleterm=0;
int counttwoxterms=0;
while(!cin.eof)
{
a*x*x+b*x+c;
}
if (a==0),
countdataisinvalid++;
{
cout << "A is 0, data invalid." << endl;
}
else if, (discriminant < 0),
countdataisinvalid++;
{
cout << "The square is a negative number, data invalid." << endl;
}
else,
countdataisvalid++;
{
cout << " Data set is valid." << endl;
}
if (c==0),
countnolastterm++;
{
cout << "C is 0, there is no last term." << endl;
}
{
x1 = (-b + sqrt(b*b-4*a*c))/(2*a);
x2 = (-b - sqrt(b*b-4*a*c))/(2*a);
cout.precision(3);
}
if (x1==x2),
countonexvalue++;
{
cout << "Only one x value." << endl;
}
else, if (x1==-x2),
countnomiddleterm++;
{
cout << "There is no middle term." << endl;
}
else
counttwoxterms++;
{
cout << "There are two x values." << endl;
}
{
y = a*x1*x1+b*x1+c
y = a*x2*x2+b*x2+c
cout << "When x is " << x << "y is " << y << endl;
}

Your code contains too many errors. You should learn C++ again with writing simple programs.
At least this code compiles.
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <math.h>
using namespace std;
int main ()
{ // use { to begin definition of function, not ;
// initialize ariables for in case the reading fails
int a = 0, b = 0, c = 0, x = 0, y = 0;
int discriminant = 0;
double x1 = 0, x2 = 0;
int countdataisinvalid=0;
int countdataisvalid=0;
int countnolastterm=0;
int countonexvalue=0;
int countnomiddleterm=0;
int counttwoxterms=0;
// you should read numbers instead of writing possibly infinite loop and meaningless statement
cin >> a >> b >> c >> x >> discriminant >> x1 >> x2;
if (a==0) // remove extra comma
{
countdataisinvalid++; // move this statement to right position
cout << "A is 0, data invalid." << endl;
}
else if (discriminant < 0) // remove extra commas
{
countdataisinvalid++; // move this statement to right position
cout << "The square is a negative number, data invalid." << endl;
}
else // remove extra comma
{
countdataisvalid++; // move this statement to right position
cout << " Data set is valid." << endl;
}
if (c==0) // remove extra comma
{
countnolastterm++; // move this statement to right position
cout << "C is 0, there is no last term." << endl;
}
{
x1 = (-b + sqrt(b*b-4*a*c))/(2*a);
x2 = (-b - sqrt(b*b-4*a*c))/(2*a);
cout.precision(3);
}
if (x1==x2) // remove extra comma
{
countonexvalue++; // move this statement to right position
cout << "Only one x value." << endl;
}
else if (x1==-x2) // remove extra commas
{
countnomiddleterm++; // move this statement to right position
cout << "There is no middle term." << endl;
}
else
{
counttwoxterms++; // move this statement to right position
cout << "There are two x values." << endl;
}
{
y = a*x2*x2+b*x2+c; // add semicolon and remove useless statement
cout << "When x is " << x << "y is " << y << endl;
}
return 0; // add a statement to return some value
} // add this as end of definition of function

Related

Program that finds the number you are thinking doesn't work properly, what is wrong?

Im having trouble with this recursion code. Basically I want the computer to "guess" in as little steps as possible the number that I am thinking of. However, everything works except the final output. The bounds are fine, and it narrows down the guess until it asks me if the number im thinking of is say 16, if I input "=" it should output 16 instead it always outputs 50. Could anyone help me locate the error?
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
unsigned int search (unsigned int boundInf, unsigned int boundSup);
int main ()
{
int b;
b = search (1, 100);
cout << "Your number must be : " << b << endl;
}
unsigned int search (unsigned int boundInf, unsigned int boundSup)
{
string magnitude;
int b;
b = (boundSup + boundInf) / 2;
cout << "Is your number <, > or = to " << b << "? ";
cin >> magnitude;
if (magnitude == "<") {
cout << "Between " << boundInf << " and " << b << endl;
search (boundInf, b);
}
else if (magnitude == ">") {
cout << "Between " << b << " and " << boundSup << endl;
search (b, boundSup);
}
return b;
}
You forgot to change the value of b when going deeper into the recursive function, this can be easily fixed by changing the search function like so:
unsigned int search(unsigned int boundInf, unsigned int boundSup)
{
string magnitude;
int b;
b = (boundSup + boundInf) / 2;
cout << "Is your number <, > or = to " << b << "? ";
cin >> magnitude;
if (magnitude == "<")
{
cout << "Between " << boundInf << " and " << b << endl;
b = search(boundInf, b);
}
else if (magnitude == ">")
{
cout << "Between " << b << " and " << boundSup << endl;
b = search(b, boundSup);
}
return b;
}

Recursive function showing segmentation issue C++

This code is for recursive function practice. When I run the code, it stops at the "POWER" cout line, then my compiler shows a segmentation error. The function that follows the POWER line is supposed to recursively raise number "a" to the power of number "b". I'm not sure how to fix this, can anyone help?
#include <iostream>
#include <string>
#include <vector>
using namespace std;
/**** Recursive backwards print, prints a string starting from last index to first*****/
void printReverse(string s, int i)
{
if(i < s.size())
{
printReverse(s.substr(1), i);
cout<<s[i];
}
else
{
return;
}
}
/**** Recursive power function, computes a^b, where b can be positive or negative*****/
int recPower(double a, int b)
{
int i = b; //i = b, so int a can be multiplied int b times
if (i == 0) //base
return 1;
else //multiply A by B, B times
{
a *= b;
return recPower(a, b); //recursive
i--; //decrement i until it equals 0
}
}
/**** Recursive string replace, replaces all instances of a character in a string with another character*****/
string recReplace(string s2, int i, char old, char neW)
{
if(s2[i] == old) //search for old char
{
i = neW; //replace it
i++; //iterate i
}
recReplace(s2, i, old, neW); //call function
return s2;
}
/**** Recursive list find > Searches if x exists in list, returns true if found, false otherwise*****/
int recListFind(vector<int> v, int i, int x)
{
if(v[i] == x)
{
cout << x << " exists in the vector."<<endl;
i++;
recListFind(v, i, x);
}
return true;
}
int main()
{
cout << "PRINT REVERSE" << endl;
cout << "----------" << endl;
string s1 = "hello world";
cout << "String: " << s1 << endl;
cout << "Reversed: ";
printReverse(s1, 0);
cout << endl;
/* Computes a^b (power function) */
cout << "POWER" << endl;
cout << "----------" << endl;
int a = 2, b = -3;
cout << a << "^" << b << " = ";
cout << recPower(a, b) << endl;
cout << endl;
/* Replaces a character in a string with a new one */
cout << "REPLACE" << endl;
cout << "----------" << endl;
string s2 = "-h-e-l-l-o-";
char oldChar = '-';
char newChar = ' ';
cout << "String: " << s2 << endl;
cout << "> Replace '" << oldChar << "' with '" << newChar << endl;
recReplace(s2, 0, oldChar, newChar);
cout << "String: " << s2 << endl;
cout << endl;
/* Searches for value in vector */
cout << "FIND" << endl;
cout << "----------" << endl;
int x = 7;
cout << "Does " << x << " exist in the vector? "; vector<int> v = {5, 1, 6, 7, 9};
cout << recListFind(v, 0, 7) << endl;
cout << endl;
return 0;
}
The issue is quite straight forward, you are doing the recPower function with b. In the function, if b is not 0, you call recPower with an unmodified value of b (whilst ever modifying a). This will always end up with infinite recursion which is going to overflow your stack.
A solution could be:
int recPower(double a, int b, int times) {
if (times == 0)
return a;
else
return b * recPower(a, b, --times);
}
int recPower(double a, int b) {
return recPower(a, b, b);
}
Even if you fix this, you have another problem. b can be negative, which based on your logic will continue to recurse while decrementing until it overflows and goes back to 0. You will cause this case with your first test case. You should think about the types that are allowed in this function, consider making them unsigned, or dealing explicitly with the negative b case.

warning C4018: '<': signed/unsigned mismatch ONLY when I include Identical Functions

I am lost, when I ran my program last night it ran fine. When I added the power() function, suddenly lines which ran fine without adding the new code now trigger an error message:
warning C4018: '<': signed/unsigned mismatch
Why?
I feel I don't have the chops to explain this, so please follow the code below.
PLEASE RUN THE CODE WITH AND WITHOUT THIS power() FUNCTION. When run with the power() function, it makes error C4018 on the for loops in the exam() function! When run without the power() function, it runs FINE!!
#include <string>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <cmath>
#include <numeric>
using namespace std;
///the offending function///
double power(double base, int exponent)
{
double product;
//double base; int exponent;
std::cout << "enter a value for base: " << endl;
std::cin >> base;
std::cout << "enter exponenent: " << endl;
std::cin >> exponent;
double result = 1;
for (int i = 0; i < exponent; i++)
{
result = result * base;
//product = base exponent;
}
std::cout << product;
return product;
}
///after here, things run fine if you X out the aforementioned function! Wow!
void exam()
{
std::vector<int> scores;
int F;
F = 0; //string names;
std::cout << "enter exam scores int:" << endl;
//std::vector <string> names;
while (F != -1)
{
std::cout << "Enter a new exame score:" << endl;
std::cin >> F;
scores.push_back(F);
}
if (F == -1)
{
std::cout << "end of score entering" << endl;
}
for (int i = 0; i < scores.size(); i++)
{
std::cout << scores[i];
}
/*
while (i < scores.size())
{
std::cout << scores[i];
i++;
}
*/
std::cout << "yay you made this work!!!!!!!!!!!!!" << endl;
}
int multiply()
{
int a;
int b;
a = 8;
b = 4;
std::cout << a * b << endl;
std::cout << "f*** yeah" << endl << endl;
return 0;
}
void test()
{
std::vector<int> newvector;
int T;
std::cout << "enter vector variables: " << endl;
std::cin >> T;
newvector.push_back(T);
while (T != -1)
{
std::cout << "enter new vector variables T " << endl;
std::cin >> T;
newvector.push_back(T);
if (T == -1)
{
newvector.pop_back();
}
}
std::cout << "end of NewVector data inputs:" << endl;
for (int W = 0; W < newvector.size(); W++)
{
std::cout << newvector[W] << endl;
}
}
int main()
{
power(2, 3);
exam();
/*int result = multiply();
std::cout << "endl ;" << endl;
test();
system("pause"); */
multiply();
string name;
int a;
std::cout << "enter a variable for your name: " << endl;
std::getline(cin, name);
if (name == "aaron")
{
std::cout << " what a dumb name, aAron?" << endl;
}
else if (name == "todd")
{
std::cout << "what a dottly name, Todd" << endl;
}
else
{
std::cout << "your name = " << name << endl;
}
//std::vector <string>
std::vector<int> asdf;
std::cout << "enter an int for a" << endl;
std::cin >> a;
asdf.push_back(a);
while (a != -1)
{
std::cout << "enter another A: " << endl;
std::cin >> a;
asdf.push_back(a);
if (a == -1)
{
asdf.pop_back();
}
} //set var; checks if d<size(); if so, JUMP to std::cout<<; when finished with body, find after size(); == "d++", then refer back to declaration)
/*/ for(int G = 0; G<asdf.size(); G++)
{
std::cout << asdf[G] << endl;
} */
for (int i = 0; i < asdf.size(); i++)
{
std::cout << asdf[i] << "f*** it works!!!!!! " << endl;
}
for (int d = 0; d < asdf.size(); d++)
{ //htt ps://youtu.be/_1AwR-un4Hk?t=155
std::cout << asdf[d] << ", ";
}
std::cout << endl;
std::cout << std::accumulate(asdf.begin(), asdf.end(), 0);
//std::cout<<
system("pause");
return 0;
}
The presence of the power function should have no effect on this problem. Possibly you aren't seeing the warnings because without the power function the program does not compile.
In
for (int W = 0; W < newvector.size(); W++)
newvector.size() returns an unsigned integer. int W is a signed integer. You're getting exactly what you asked for.
You can change int W to vector<int>::size_type W (but the less verbose size_t W should also work) to make the error message go away, but this is an error where you would likely have to add more than 2 billion items to the vector to see manifest.
Solution:
for (vector<int>::size_type W = 0; W < newvector.size(); W++)
However this is a good place for a range-based for loop
for (const auto &val: newvector)
{
std::cout << val << endl;
}
By letting the compiler figure out all the sizes and types your life is much easier.
This is repeated several times throughout the code.
Re: WHEN RUN, It makes error C4018 -
YOU made that error (warning, actually), not "it".
That warning is reported by compiler, so you haven't run anything yet...
Your newly added function uses uninitialized variable product; in my version of Visual Studio it is an error.

simplify my code in C++ below

I want to create a program which is able to calculate the surface area, volume, and circumference. for your additional info, I am studying about function, I has just learned about C++ about a week.
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int getPostP(string msgP)
{
int Ppost= 0.000;
do
{
cout << msgP << endl;
cin >> Ppost;
return Ppost;
} while(Ppost<= 0);
}
int getPostL(string msgL)
{
int Lpost= 0.000;
do
{
cout << msgL << endl;
cin >> Lpost;
return Lpost;
} while(Lpost<= 0);
}
int getPostT(string msgT)
{
int Tpost = 0.000;
do
{
cout << msgT << endl;
cin >> Tpost;
return Tpost;
} while(Tpost <= 0);
}
int surfaceArea(int Psur, int Lsur, int Tsur)
{
return (2*Psur*Lsur)+(2*Psur*Tsur)+(2*Lsur*Tsur);
}
int volume(int Pvol, int Lvol, int Tvol)
{
return (Pvol*Lvol*Tvol);
}
float circumference(int Pcir, int Lcir, int Tcir)
{
return 4*(Pcir+Lcir+Tcir);
}
int main()
{
int P = getPostP("enter the P of your block");
int L = getPostL("enter the L of your block");
int T = getPostT("enter the T of your block");
float surfAreaBlock = surfaceArea(P, L, T);
float volBlock = volume(P, L, T);
float cirBlock = circumference(P, L, T);
cout << "block which have P = " << P << " and L = " << L << " and T = "<< T << " have surface area = " <<
surfAreaBlock << " and volume = " << volBlock << " and cirBlock = " << cirBlock;
return 0;
}
Maybe one of you want to rewrite and add some comment, which parts are able to simplify, so I can understand easier.
First of all, it looks like you should make all of your integer inputs into double instead of int, since it's expected that your inputs won't necessarily be an exact integer amount (probably). Also you can get rid of all of your duplicate functions for entering the parameters. Change it to a single function and call that one for each variable.
double getInput(const std::string& prompt)
{
double input(0.0);
do
{
std::cout << prompt << "\n-> " << std::flush;
// forces input to be a double type
while (!(std::cin >> input))
{
std::cout << "\n-> " << std::flush;
std::cin.clear();
std::cin.ignore(256, '\n'); ///< could use streamsize::max here
}
} while (input <= 0.0); ///< make sure it's positive
return input;
}

Converting Object int data members to floating point and dividing appends strange data cout to console

I'm sure I'm doing something wrong, but I just can't figure it out. I've created an object with integer data members, and I want to have a member function return the quotient of it's members as a floating point value, which it does. It then appends some additional stuff. The output is below the program, which should run as is.
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
class Rational
{
public:
explicit Rational(int = 0, int = 1);
double getRationalAsDouble() const;
private:
int numerator;
int denominator;
};
Rational::Rational(int numerator, int denominator)
{
if (denominator == 0)
this->denominator = 1;
else
this->denominator = denominator;
this->numerator = numerator;
}
// ******* Problem Function *********
double Rational::getRationalAsDouble() const
{
double a = 0.0, b = 0.0;
a = static_cast<double>(numerator);
b = static_cast<double>(denominator);
cout << endl << "a = " << a;
cout << endl << "b = " << b;
cout << endl << "a/b = " << (a/b);
}
// ******** End Problem Function ********
int main()
{
{ //Create a new Scope so that I can view Destructor Message, not used here
Rational c(2, 6);
int data = 10;
cout << c.getRationalAsDouble(); // prints rational object c as double, but not really
cout << "\n\n";
} // End of Scope
return 0;
} // end main
And here's the output:
a = 2
b = 6
a/b = 0.3333332.31196e-317
I've been playing around, and if I change the function to have any regular division in it, it works fine. What's really interesting is if I add any output after the cout << endl << "a/b = " << (a/b); line, that output is handled before (a/b) part of the line. Any help would be greatly appreciated! Thank you in advance for your time.
Solution:
The function wasn't returning anything. When the code was changed to:
double Rational::getRationalAsDouble()
{
return static_cast<double>(numerator)/denominator;
}
It worked as expected. Thank you tc.
Three problems:
You want to print endl at the end of the line, not the "beginning". Your code ends up doing (effectively) cout << endl << "a/b = " << (a/b); ... cout << c.getRationalAsDouble(); cout << "\n\n"; which prints the two doubles 0.333333 and 2.31196e-317 next to each other with no space.
You want (perhaps) cout << "\n" << endl instead of cout << "\n\n". endl causes the stream to be flushed; plain "\n" might not.
Rational::getRationalAsDouble() is not returning a value. Listen to your compiler warnings.
The fix looks something like
double Rational::getRationalAsDouble() const
{
double a = 0.0, b = 0.0;
a = static_cast<double>(numerator);
b = static_cast<double>(denominator);
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "a/b = " << (a/b) << endl;
return a/b;
}
Your implementation of Rational::getRationalAsDouble() can be simplified to:
double Rational::getRationalAsDouble() const
{
return 1.0*numerator/denominator;
}
I think you had everything else there for debugging purposes, and hence are not really needed.