I try running this code but the problem is -since I'm a beginner - I don't know how to place several conditions in one if statement and why the if line and else linke have errors. Can you please show me where I went wrong ? Thanks
#include <iostream>
using namespace std;
int main(){
double AVG;
cout<< "please write in average\n";
cin>> AVG;
if ((AVG >60) && (AVG >=90))----------expected identifier
cout<< "pass with grade of " << AVG ;
cout << "\n" << "A star!\n";
else----------------------------------expected expression
cout << "fail with grade of " << AVG << "\n";
cout<< "good luck with your smester !\n";
}
May be this could help you and there is no need to add (AVG >60) && (AVG >=90) both as if AVG>=90 then AVG >60 is true already.
#include <iostream>
using namespace std;
int main(){
double AVG;
cout<< "please write in average\n";
cin>> AVG;
if (AVG >=90)
{
cout<< "pass with grade of " << AVG ;
cout << "\n" << "A star!\n";
}
else
{
cout << "fail with grade of " << AVG << "\n";
cout<< "good luck with your smester !\n";
}
return 0;
}
If you are using more than one statement please use parenthesis and you are using int main() then you need to return a value.
Updated Code
#include <iostream>
using namespace std;
int main(){
double AVG;
cout<< "please write in average\n";
cin>> AVG;
if ((AVG >60) && (AVG >=90))
{
cout<< "pass with grade of " << AVG ;
cout << "\n" << "A star!\n";
}
else{
cout << "fail with grade of " << AVG << "\n";
cout<< "good luck with your smester !\n";
}
return 0;
}
Hope this helps
Related
at the moment I'm trying to add up the numbers for my hand and the hit cards, the issue is I created a function for my random number generator so that I can keep calling it into my dice game and the blackjack game, I would normally add the number generator to a variable and call it a day but I made it into a function instead. I am still new to c++.
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
void RandomNumber() { cout << (rand() % 10) + 1; }
void blackjack(int total) {
int startstakes = 15;
int stakes;
int hand;
cout << "Welcome to the Blackjack(21) table\n"
<< "How much are you adding to your initial 15 chip stake - ";
cin >> stakes;
cout << "New stake - " << stakes + 15 << " remaining chips - "
<< total - (stakes + 15) << endl;
cout << "Here is your hand - ";
RandomNumber();
cout << " and ";
RandomNumber();
cout << "Hit me cards: 0 - 0 - 0\n"
<< "Total = ";
system("pause>0");
}
int main() {
int total = 0;
int choice;
srand((unsigned)time(NULL));
cout << "Welcome to Royal Casino!!!, How much money do you wish to "
"convert? ";
cin >> total;
cout << "Excelent you currently have " << total << " Chips.\n"
<< "Let's Begin!\n\n"
<< "We have to tables available today\n";
cout << "1) Blackjack (21)\n"
<< "2) Dice\n"
<< "Both have an entry fee of 15 Chips\n"
<< "Select a table - ";
cin >> choice;
if (choice == 1) {
blackjack(total);
}
if (choice == 2) {
dice();
}
system("pause");
}
So the issue is that you should return the value instead of printing it. Like this (note the return type has changed from void to int)
int RandomNumber() {
return (rand() % 10) + 1;
}
A function which returns a value is much more flexible than a function which prints a value.
Now you can use a function call RandomNumber() pretty much the same way as a variable. E.g.
cout << RandomNumber() << " and " << RandomNumber();
or
int var = RandomNumber();
I am working on a project that involves creating a menu screen, and integrating three programs into one that can be selectively launched from the menu screen.
I thought making individual programs first before piecing them together with switch case and functions would be easy (I don't know class/objects). I keep running into a brick wall and a host of syntax/logical errors, so I deleted everything and now I'm back to square one-- with three distinct programs. This is very daunting-- how do proceed? :/
#include <iostream>
using namespace std;
int main ()
{
int x;
cout << "Enter the amount of money you have ";
cin >> x;
if (x >= 20) {
cout << "You can buy Comic Book $1 or Sports Journal $3 or Science Book $15 or Third Volume Series $20";
} else if (x >= 15 && x < 20) {
cout << "You can buy Comic Book $1 or Sports Journal $3 or Science book $15";
} else if (x >= 3 && x < 15) {
cout << "You can buy Comic Book $1 or Sports Journal $3";
} else if (x >= 1 && x < 3) {
cout << "You can buy Comic Book $1";
} else if (x <= 0) {
cout << "You cannot afford anything";
}
return 0;
}
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
int main()
{
int numclass; //number of classes
int numStudents; //number of students
int numTests; // Number of tests per student
double sectiontotal; //Accumulator for Class total scores
double total; // Accumulator for total scores
double average; //Average test score
double totalaverage = 0;
ofstream outfile;
outfile.open("Gradesinfo.txt");
// Set up numeric output formatting.
cout << fixed << showpoint << setprecision(1);
// Get the number of students.
cout << "This program gives average of test scores per student, per class, and for the whole institution for upto 2 students in upto 2 different classes in 3 subjects\n";
// Determine each student's average score.
cout << "Enter the number of classes";
cin >> numclass;
cout << "Enter the number of students per class";
cin >> numStudents;
cout << "Enter the number of tests";
cin >> numTests;
for (int section = 1; section <= numclass; section++) {
sectiontotal = 0; //Initialize class accumulator
totalaverage = 0;
for (int student = 1; student <= numStudents; student++) {
total = 0; // Initialize the accumulator.
for (int test = 1; test <= numTests; test++) {
double score;
cout << "Enter score " << test << " for ";
cout << "student " << student << ": ";
cin >> score;
if (score >= 0 && score <= 100) {
total += score;
} else {
cout << "Enter value from 1 - 100" << endl;
test = test - 1;
}
}
average = total / numTests;
totalaverage += average;
cout << "The average score for student " << student;
cout << " is " << average << ".\n\n";
outfile << "The average score for student " << student;
outfile << " is " << average << ".\n\n";
}
cout << "The total average for class " << section << " is: " << totalaverage / numStudents << endl;
outfile << "The total average for class " << section << " is: " << totalaverage / numStudents << endl;
sectiontotal += totalaverage;
}
cout << "The total average for the institution is: " << sectiontotal / numclass;
outfile << "The total average for the institution is: " << sectiontotal / numclass;
outfile.close();
return 0;
}
#include<cstdlib>
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
fstream instream;
ofstream outstream;
instream.open("Grades.txt");
if (instream.fail()) {
cout << "The input file failed to open\n";
exit(1);
}
int next, largest, smallest;
largest = 0;
smallest = 0;
while (instream >> next) {
if (largest < next) {
largest = next;
} else {
smallest = next;
}
}
cout << "The highest grade is: " << largest << endl;
instream.close();
system("pause");
return 0;
}
I think you are shooting yourself on the foot. go 1 step after the other, please do take this as reference:
create a main file as entry point for the app, note the prototype and implementation of the functions printA and printB
#include <iostream>
using namespace std;
void printA();
void printB();
int main()
{
int x = 1;
cout << "Enter the option:\n";
while (cin >> x)
{
if (x <= 0)
{
break;
}
switch (x) {
case 1:
printA();
break;
case 2:
printB();
break;
default:
cout << "Invalid";
}
}
return 0;
}
void printB()
{
cout << "B";
}
void printA()
{
cout << "A";
}
create a new file fooA.cpp and paste there the implemented function printA
do the same for the printB in another file.
remove those implementations from main.cpp
you are done!
I'm working on a project by where I have to create a simple program that works based of the user input. I've gone with a basic calculator but I'm having trouble getting my if/else if statements to work. Basically, if the user types in "Addition", I want the program to say "...I will help you with addition!", and so on for whether the user says "Subtraction", "Division", and "Multiplication".
I'm new to this and so this has already taken me hours upon hours, not looking for you to do it for me but to point out my erorrs and advise so that I can learn from it will be great.
TIA.
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <iomanip>
using namespace std;
//user inputs what he needs help with/program output
char Inpsum()
{
cout << "Hello, my name is Eva! I am able to help you with basic Maths! How may I be of assistance today?" << endl;
char inpsum[20];
cin >> inpsum;
char output;
if (inpsum == "Addition")
{
cout << "Great! I'll help you with addition!" << endl;
}
else if (inpsum == "Subtraction")
{
cout << "Great! I'll help you with subtraction!" << endl;
}
else if (inpsum == "Division")
{
cout << "Great! I'll help you with division!" << endl;
}
else if (inpsum == "Multiplication")
{
cout << "Great! I'll help you with multiplication!" << endl;
}
return 0;
REST OF CODE
//addition function
void Add() {
float add1, add2;
cout << "Please enter two values you want added together" << endl;
cin >> add1;
cin >> add2;
cout << "The answer is: " << (add1 + add2) << endl;
}
//subtraction function
void Subt() {
float subt1, subt2;
cout << "Please enter two values you want subtracted" << endl;
cin >> subt1;
cin >> subt2;
cout << "The answer is: " << (subt1 - subt2) << endl;
}
//division function
void Div()
{
float div1, div2;
cout << "Please enter two values you want divided" << endl;
cin >> div1;
cin >> div2;
cout << "The answer is: " << (div1 / div2) << endl;
}
//multiplication function
void Mult() {
float mult1, mult2;
cout << "Please enter two values you want multiplacted" << endl;
cin >> mult1;
cin >> mult2;
cout << "The answer is: " << (mult1 * mult2) << endl;
}
int main()
{
Inpsum(); //user inputs what they want help with
Add();
Subt();
Div();
Mult();
return 0 ;
}
This code is all wrong you need to learn about C++ correctly first, here is the corrected code
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <iomanip>
#include<string>
using namespace std;
//addition function
float Add(float add1, float add2)
{
return (add1 + add2);
}
//subtraction function
float Subt(float subt1, float subt2) {
return (subt1 - subt2);
}
//division function
float Div(float div1, float div2)
{
return (div1 / div2);
}
//multiplication function
float Mult(float mult1, float mult2)
{
return (mult1 * mult2);
}
void input(float &num1, float &num2)
{
cout << "\nEnter First Number : ";
cin >> num1;
cout << "Enter Second Number : ";
cin >> num2;
}
//user inputs what he needs help with/program output
void Inpsum()
{
cout << "Hello, my name is Eva! I am able to help you with basic Maths! How may I be of assistance today?" << endl;
float num1;
float num2;
string inpsum;
cin >> inpsum;
if (inpsum == "adding")
{ //if user enters "adding"
cout << "Great!, I will help you with " << (inpsum) << endl;
input(num1, num2);
cout << "\nAnser Is " << Add(num1, num2);
}//then output = "...i will help with adding"
else if (inpsum == "subtraction") //otherwise, if user enters "subtraction"
{
cout << "Great!, I will help you with " << (inpsum) << endl; //then output = "...i will help with subtraction"
input(num1, num2);
cout << "\nAnser Is " << Subt(num1, num2);
}
else if (inpsum == "division") //if user enters "division"
{
cout << "Great!, I will help you with " << (inpsum) << endl; ////then output = "...i will help with division
input(num1, num2);
cout << "\nAnser Is " << Div(num1, num2);
}
else if (inpsum == "multiplication") //if user enters "muliplication"
{
cout << "Great, I will help you with " << (inpsum) << endl; ////then output = "...i will help with multiplication"
input(num1, num2);
cout << "\nAnser Is " << Mult(num1, num2);
}
else
{
cout << "Enter A Correct Mathematical Operation";
}
}
int main()
{
Inpsum(); //user inputs what they want help with
cout<<endl;
system("pause");
return 0;
}
First of all, instead of using char array, use std::string.
Secondly, if-else statements have syntax errors.
Basic structure of if-else statements is like
if(condition)
{
//code
}
else
if(condition)
{
//code
}
More on if-else statements in C++
Hello everyone I'm trying to find the average of a random amount of numbers that are input into a loop. For sum reason after the loop im able to print the right total, but when i try to find the average i get a weird answer. can anyone help me with this or direct to a thread on here that could help? I wasnt able to find anything on here.
here is my code for the program that isnt working.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream inData;
string golferFile;
string golfer;
int matches;
int score;
cout << endl;
cout << "Enter the golfer's filename: ";
cin >> golferFile;
inData.open(golferFile.c_str());
getline(inData, golfer);
inData >> matches;
cout << endl;
cout << "The golfer " << golfer << " has " << matches << " matches with scores"
" of" << endl;
cout << endl;
int count;
count = 1;
int matchNumber;
matchNumber = 1;
int sum;
while(count <= matches)
{
inData >> score;
cout << "Match " << matchNumber << ": " << score << endl;
matchNumber++;
count++;
sum = sum + score;
}
}
int mean;
mean = sum / matches;
cout << "The mean score is " << mean << endl;
return 0;
}
the output i receive is this for the mean
The mean score is 1399255
I found several error in your code.
you forget to initialize your sum variable.
in while loop an extra brace found.remove it
you didn't write anything to stop your loop.that why your loop run infinite time.so initialize you loop also.
I am struggling to get an input validation working for my game.
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
int iGumballs;
int iUserguess;
int iGuesses = 0;
while (true)
{
system("CLS");
cin.clear();
iGuesses = 0;
srand(static_cast<unsigned int>(time(0)));
iGumballs = rand()%1000+1;
cout << "How many gumballs are in the bumball jar? You guess! 1-1000" << endl;
do
{
cout << "Enter your guess: ";
cin >> iUserguess;
if(iUserguess > iGumballs)
{
cout << "Too high!" << endl << endl;
}
if(iUserguess < iGumballs)
{
cout << "Too low!" << endl << endl;
}
iGuesses ++;
}
while(iUserguess > iGumballs || iUserguess < iGumballs);
cout << "You guessed the right amout of gumballs" << endl << endl;
cout << "You took " << iGuesses << " guesses" << endl << endl;
system ("pause");
}
return 0;
}
I basically want the program to display
Your Guess: Sorry, incorrect input - try again
When the user enters a number less then 1, and higher then 1000, as well as some sort of validation which makes sure a number is entered instead of a letter or symbol. I tried cin.fail() but I couldn't get it quite to work.
Thanks,
John
You will need some test to see if is a number or not, try this:
#include <iostream>
#include <string>
#include <ctime>
#include <boost/lexical_cast.hpp> //dependency that can be optional
using namespace std;
bool is_number(const std::string& s)
{
std::string::const_iterator it = s.begin();
while (it != s.end() && std::isdigit(*it)) ++it;
return !s.empty() && it == s.end();
}
int main()
{
int iGumballs;
std::string iUserguessStr;
int iUserguess;
int iGuesses = 0;
while (true)
{
system("CLS");
cin.clear();
iGuesses = 0;
srand(static_cast<unsigned int>(time(0)));
iGumballs = rand()%1000+1;
cout << "How many gumballs are in the bumball jar? You guess! 1-1000" << endl;
do
{
cout << "Enter your guess: ";
cin >> iUserguessStr;
if(is_number(iUserguessStr))
iUserguess = boost::lexical_cast<int>(iUserguessStr); //you can make your own or maybe use lexical cast to transform a string into integer
else
continue; //put some fancy message here warning the user
if(iUserguess > iGumballs)
{
cout << "Too high!" << endl << endl;
}
if(iUserguess < iGumballs)
{
cout << "Too low!" << endl << endl;
}
iGuesses ++;
}
while(iUserguess > iGumballs || iUserguess < iGumballs);
cout << "You guessed the right amout of gumballs" << endl << endl;
cout << "You took " << iGuesses << " guesses" << endl << endl;
system ("pause");
}
return 0;
}
My answer is based on a related problem: How to determine if a string is a number with C++?
Yo can use if(cin) to check the state of the input stream and since operator>> will return the input stream that was passed to it you can use if(cin>>iUserguess)
If cin is in a failed state -maybe because the user entered a non number- the expression if(cin>>iUserguess) will evaluate to false.
If the user enters a non number you will need to call cin.clear() to clear the stream state and cin.ignore() to discard the input, before trying to read a number again.
so using your example, it could be changed to this:
#include <iostream>
#include <ctime>
#include <limits>
using namespace std;
int main()
{
int iGumballs;
int iUserguess;
int iGuesses = 0;
while (true)
{
system("CLS");
iGuesses = 0;
srand(static_cast<unsigned int>(time(0)));
iGumballs = rand()%1000+1;
cout << "How many gumballs are in the bumball jar? You guess! 1-1000" << endl;
do
{
cout << "Enter your guess: ";
if(cin >> iUserguess)
{
iGuesses ++;
if(iUserguess > iGumballs)
{
cout << "Too high!" << endl << endl;
continue;
}
if(iUserguess < iGumballs)
{
cout << "Too low!" << endl << endl;
continue;
}
}
else
{
cout<<"incorrect input - try again\n\n";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
continue;
}
}
while(iUserguess > iGumballs || iUserguess < iGumballs);
cout << "You guessed the right amout of gumballs" << endl << endl;
cout << "You took " << iGuesses << " guesses" << endl << endl;
system ("pause");
}
return 0;
}
To validate characters you could use the try-catch structure.
-First read in a string and try Typecasting it and handle the errors with try-catch.
-Then use conditions to make sure the input is in range.
-If the input isn't valid, you can write an error message to display.