Main not returning 0 [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
So I have this exercise, I need to ask the user for 2 inputs (grades >0 <10) and then I have to print the average and then ask the user if they want to insert more grades 1-yes 2-no; if it's 1 then the program runs again, if it's 2 the program quits. But I'm having trouble to make the program quit.
// ConsoleApplication7.cpp : Defines the entry point for the console application.
//
#include <iostream>
#include "stdafx.h"
int main()
{
using namespace std;
float n1;
float n2;
cin >> n1;
cin >> n2;
if ((n1 || n2) > 10) {
cout << "Wrong grade";
}
else if ((n1 || n2) < 0) {
cout << "Wrong grade";
}
else {
cout << "The grade average is " << (n1 + n2) / 2 << endl;
cout << "Do you want to insert more grades ? " << endl;
int g;
cin >> g;
if (g = 1) {
main();
}
else if (g = 2) {
return 0;
}
}
return 0;
}

The problem is to test for equality you need two =, not one so your two checks are actually assigning values to g not comparing with g
if (g == 1) {
main();
}
else if (g == 2) {
return 0;
}
Any modern compiler should have given you a compiler warning about that assignment. You should always try to pay attention to compiler warnings.
Also your logic of
if ((n1 || n2) > 10)
and
else if ((n1 || n2) < 0)
is incorrect, but I will leave it to you to figure out what is wrong (this is homework afterall).
Lastly you may want to look in to doing a do-while loop instead of calling main() over and over.

Your ifcondition is wrong:
if (g = 1)
sets g to 1, and is always true. What you want to do is:
if (g == 1)
And as Scott said in his comment, you shouldn't call main but rather use a while loop.

Please look at these modifications.
float n1;
float n2;
int g = 1;
while (g != 2)
{
cout << "Please enter two grades: " << endl;
cin >> n1;
cin >> n2;
if ((n1 || n2) > 10) {
cout << "Wrong grade";
}
else if ((n1 || n2) < 0) {
cout << "Wrong grade";
}
else {
cout << "The grade average is " << (n1 + n2) / 2 << endl;
cout << "Do you want to insert more grades ? " << endl;
cin >> g;
}
}
return 0;
}
Also note that I moved using namespace outside of main.

Related

I keep getting an error saying invalid types int[int] for array subscript [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 months ago.
Improve this question
Sorry if my code is garbage, I just started programming, and I'm sure there are quite a few things I'm doing wrong. Please also let me know on how I can improve this. I'm trying to create a program that checks the password a user enters. Right now I keep getting an invalid types error. Would appreciate any help:)
#include <iostream>
#include <vector>
#include <cstring>
#define N 20
// Program that checks for a secure password so far
class Password
{
public:
char UserPassword[N];
int MenuChoice;
int Length;
int LowerCaseAmount = 0;
int UpperCaseAmount = 0;
int DigitAmount = 0;
int SpecialCharAmount = 0;
void Menu()
{
std::cout << "1. Check my current password \n"
<< "2. Generate me a secure password \n"
<< std::endl;
std::cin >> MenuChoice;
if (MenuChoice == 1)
{
//
}
else if (MenuChoice == 2)
{
//
}
else
{
std::cout << "INVALID OPTION! ";
}
}
void CheckPassword()
{
std::cout << "Enter your current password : \n";
std::cin.ignore();
std::cin >> UserPassword;
if (strlen(UserPassword) >= 10)
{
Length = strlen(UserPassword);
for (int i=0; i<Length; i++)
{
if (Length[i] == 'a' && Length[i] == 'z') ++LowerCaseAmount;
if (Length[i] == 'A' && Length[i] == 'Z') ++UpperCaseAmount;
if (Length[i] == '0' && Length[i] == '9') ++DigitAmount;
if (Length[i] == '!' && Length[i] == '*') ++SpecialCharAmount;
}
if (LowerCaseAmount > 0 && UpperCaseAmount > 0 && DigitAmount > 0 && SpecialCharAmount > 0)
{
std::cout << "Secure! ";
}
else if (LowerCaseAmount == 0)
{
std::cout << "Try adding some lower case letters! ";
}
else if (UpperCaseAmount == 0)
{
std::cout << "Try adding some upper case letters! ";
}
else if (DigitAmount == 0)
{
std::cout << "Try adding some numbers! ";
}
else if (SpecialCharAmount == 0)
{
std::cout << "Try adding some special characters! ForEX : #, $, % ";
}
}
else
{
std::cout << "Password should be ten digits or loner! "
<< std::endl;
}
}
};
int main()
{
return 0;
}
int Length;
You declared an int class member called Length.
if (Length[i] == 'a' && Length[i] == 'z')
This is using Length as if it was an array (or some container with an [] overload). Length is not an array. Length is just a plain, boring, lonely int, see above. This is the reason for your compilation error.
Looking at the overall code, it seems that you should be looking at userPassword here, which is your array (or array-like) object.

Program to calculate test scores [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 12 months ago.
Improve this question
I am writing a program to calculate the grade of 3 test scores. The lowest of the first 2 scores is dropped and added to the third test score to make the final grade. The 3 test scores cannot be higer than 50, lower than 0 and cannot be a character or string. So far, I have satisified all those requirment but I need to implement decimal grades to the program like for instance 45.5. Also to round the final grade up or down. For example if final grade is 89.5 round up to an A.
#include <iostream>
#include <algorithm>
#include <cstdlib>
using namespace std;
char getGrade(int num) {
if (num < 60)
return 'F';
if (num < 69)
return 'D';
if (num < 79)
return 'C';
if (num < 89)
return 'B';
return 'A';
}
bool isnumeric(string temp) {
for (char &chr : temp) {
if ((chr >= '0' and chr <= '9') or chr == '-')
continue;
else
return false;
}
return true;
}
int main(int argc, char const *argv[]) {
cout << "Welcome to the grade calculator.You will input three test "
"scores.\nThe highest of the first two grades and the third grade "
"will be\nadded together to determine the numeric grade average for "
"the\ncourse.Each test score has a maximum of 50 points.\n";
int arr[3];
int ctr = 0;
string temp;
int num;
while (ctr < 3) {
cout << "\nPlease enter test score " << (ctr + 1) << ": ";
label1:
cin >> temp;
if (isnumeric(temp)) {
num = atoi(temp.c_str());
if (num > 50) {
cout << "\nTest scores cannot be higher than 50, try again: ";
goto label1;
} else if (num < 0) {
cout << "\nTest scores cannot be negative, try again: ";
goto label1;
} else {
arr[ctr++] = num;
}
} else {
cout << "\nInvalid test score entered, try again: ";
goto label1;
}
}
int average = 0;
average = max(arr[0], arr[1]);
average = average + arr[2];
cout << "\nThe average for the course = " << average << "\n";
cout << "The letter grade = " << getGrade(average);
cout << "\n\n\nThank you for using this program\n";
return 0;
}
Just changed a couple of things to make it work with decimals:
1. Added chr == '.' to the isNumeric() function:
bool isnumeric(string temp) {
for (char& chr : temp) {
if ((chr >= '0' and chr <= '9') or chr == '-' or chr == '.')
continue;
else return false;
}
return true;
}
2. Changed variable types:
double arr[3]{};
int ctr = 0;
std::string temp;
double num;
3. Removed goto: (You can just use continue)
while (ctr < 3) {
std::cout << "\nPlease enter test score " << (ctr + 1) << ": ";
std::cin >> temp;
if (isnumeric(temp)) {
num = atof(temp.c_str());
if (num > 50) {
std::cout << "\nTest scores cannot be higher than 50, try again: ";
continue;
}
else if (num < 0) {
std::cout << "\nTest scores cannot be negative, try again: ";
continue;
}
else {
arr[ctr++] = num;
}
}
else {
std::cout << "\nInvalid test score entered, try again: ";
continue;
}
}
4. For rounding off, you can use std::round() as such:
double average = 0;
average = std::max(arr[0], arr[1]);
average = std::round(average + arr[2]);
You can also change your cout statements:
std::cout << "\nThe average for the course = " << average;
if (std::round(average) != average) std::cout << ", rounded off to = " << std::round(average);
std::cout << ".\nThe letter grade = " << getGrade(average);
std::cout << "\n\n\nThank you for using this program\n";
Just make all these changes and your program will successfully work with decimals.
Also, consider not using the following in your code:
using namespace std;
..as it's considered as a bad practice. For more info on why, look up to Why is using namespace std considered as a bad practice.
Edit: To accomplish your requirement, you can just change the while loop as such:
while (ctr < 3) {
if (temp.size() == 0)
{
std::cout << "\nPlease enter test score " << (ctr + 1) << ": ";
std::cin >> temp;
}
if (isnumeric(temp)) {
num = atof(temp.c_str());
if (num > 50) {
std::cout << "\nTest scores cannot be higher than 50, try again: ";
std::cin >> temp;
continue;
}
else if (num < 0) {
std::cout << "\nTest scores cannot be negative, try again: ";
std::cin >> temp;
continue;
}
else {
arr[ctr++] = num;
temp.clear();
}
}
else {
std::cout << "\nInvalid test score entered, try again: ";
std::cin >> temp;
continue;
}
}
The above code works as you said.

Why won't this C++ While loop work? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'm simply trying to get the user to put in their name/age and verify if it's correct. If not then they get 4 tries before the program will abort. However my while loops don't loop, instead they just continue on to the next loop. I've tried a variation of things inside the while parenthesis (op != 1) (!(op = 1)) etc.
int main() {
system("Color 0A");
string name;
int age;
int tries = 0;
int op = 0;
cout << "Hello User" << endl;
Sleep(3000);
while ((op != 1) && (tries < 4)) {
name = entName(name);
cout << "So your name is " << name << "?" << endl;
cout << "Enter '1' for YES or '2' for NO. ";
cin >> op;
if (op == 1) {
cout << "Perfect!";
}
if (op == 2) {
cout << "Please Try Again!";
tries+ 1;
}
if (tries = 4) {
//abort the program
}
}
int op2 = 0;
int tries2 = 0;
while ((op2 != 1) && (tries2 < 4)) {
op2 = 3;
age = entAge();
cout << "So you are " << age << " years old?" << endl;
while ((op2 != 1) && (op2 != 2)) {
cout << "Enter '1' for YES or '2' for NO. ";
cin >> op2;
if (op2 == 1) {
cout << "Perfect!\n";
}
if (op2 == 2) {
cout << "Please Try Again!\n";
tries2++;
}
if (tries2 = 4) {
//abort the programhi
}
}
}
return 0;
}
I'm fairly new to C++ so I'm sorry if it does have a simple answer. But anyway, I've been debugging this for over half an hour and I looked online for 20+ minutes.
if (tries = 4) {
//abort the program
}
Change this to
if (tries == 4) {
//abort the program
}
And
f (op == 2) {
cout << "Please Try Again!";
tries+= 1; // tries+ 1;
}
You can increment value in C++ like this tries+ 1;. Either use tries+= 1; or tries++;
tries+ 1; should be tries += 1; or tries++;
And,
if (tries = 4) {
//abort the program
}
should be:
if (tries == 4) {
//abort the program
}
Your program should look like this:
int main()
{
system("Color 0A");
string name;
int age;
int tries = 0;
int op = 0;
cout << "Hello User" << endl;
Sleep(3000);
while ((op != 1) && (tries < 4)) {
name = entName(name);
cout << "So your name is " << name << "?" << endl;
cout << "Enter '1' for YES or '2' for NO. ";
cin >> op;
if (op == 1) {
cout << "Perfect!";
}
if (op == 2) {
cout << "Please Try Again!";
tries+= 1;
}
if (tries == 4) {
//abort the program
}
}
int op2 = 0;
int tries2 = 0;
while ((op2 != 1) && (tries2 < 4)) {
op2 = 3;
age = entAge();
cout << "So you are " << age << " years old?" << endl;
while ((op2 != 1) && (op2 != 2)) {
cout << "Enter '1' for YES or '2' for NO. ";
cin >> op2;
if (op2 == 1) {
cout << "Perfect!\n";
}
if (op2 == 2) {
cout << "Please Try Again!\n";
tries2++;
}
if (tries2 == 4) {
//abort the programhi
}
}
}
You have forget to use = sign at multiple places. tries = 4 should be tries == 4 for comparing variable tries with numeric 4. tries = 4 was reassigning the variable tries to four and your while loop was getting terminated after it's first run. Also, tries + 1 should be tries += 1 or tries++ to increment the value of tries variable by one.

C++ a program to calculate the greatest profit [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
This program accepts input of the everyday prices of a good and then calculates the greatest profit. And the list of prices will end with -1.
for example, if I input 20,30,10,50,-1 , it means at the first day the good is $20,in the second day is $30,etc. The greatest profit output will be $40 since I could buy it on the third day at $10 and sell it in the fourth day at $50.
This is a school assignment and the teacher do not allow me to use array.
Now my program is fine except in this case e.g.
if I input 20 30 10, the greatest profit will be $(30-10) how could I fix it so if will not store the number after the maximum number e.g. 10 as the minimum number? Or any other codes to fulfil the purpose of my program?
#include<iostream>
using namespace std;
int main() {
int c(0), r(0), n1(0), min(0), max(0), l(0), s(0);
cout << "Please enter the prices: ";
while (n1 != -1) {
cin >> n1;
if (min == 0 && n1>0)
{
min = n1;
}
c++;
if (n1 <= 0 && n1 != -1) { cout << "Invalid. Input again. Please make sure it's a positive number!" << endl; r++; }
else {
if (n1<min && n1 != -1) { min = n1; s++; }
if (n1 >= max && (c - r)>(s + 1)) { max = n1; l = c; }
cout << c << s + 1 << l << endl;
}
}
cout << max << min;
cout << endl << "Largest amount earned: " << (max - min) << endl;
return 0;
}
You can simply calculate maximum profit by using the lowest price from now and not in the future.
#include <iostream>
int main(void) {
int lowestPrice = -1;
int highestProfit = 0;
int price, maxProfit;
while (std::cin >> price) {
if (price < 0) break;
if (lowestPrice < 0 || price < lowestPrice) lowestPrice = price;
maxProfit = price - lowestPrice;
if (maxProfit > highestProfit) highestProfit = maxProfit;
}
std::cout << highestProfit << std::endl;
return 0;
}

Why is the do - while only accepting pLife condition?

The only way the loop works is when the player runs out of lifes. The game is supposed to allow the player to answer math questions, they answer until either they, or the magician runs out of lives. So int the do while loop, the while is only working once pLife runs out, and completely ignores eLife, why is that?
do
{
int Number = rand() % 20 + 1; //Desides the random number that will be used in the program
int aNumber = rand() % 20 + 1;
int rng = rand() % 3 + 1;
cout <<"Player Life Total = " <<pLife <<endl;
cout <<"Mathmagican Life Total = " <<eLife <<endl;
if (rng == 1)
{
cout <<"What is " <<Number <<"X" << aNumber <<"?\n\n";
cin >> answer;
if (answer == Number * aNumber)
{
cout <<"What!!! How is that possible you deflected my attack!\n\n";
cout <<"Ahh it hit me!! you hit me with my own magic! Thats not fair!\n\n";
eLife = eLife- 1;
}
else if (answer > Number * aNumber, answer < Number * aNumber)
{
cout <<"I told you that you couldn't defeat me!\n\n";
cout <<"Now die!";
pLife = pLife - 1;
}
}
else if (rng == 2)
{
cout <<"What is " <<Number <<"-" << aNumber <<"?\n\n";
cin >> answer;
if (answer == Number - aNumber)
{
cout <<"What!!! How is that possible you deflected my attack!\n\n";
cout <<"Ahh it hit me!! you hit me with my own magic! Thats not fair!\n\n";
eLife = eLife- 1;
}
else if (answer > Number - aNumber, answer < Number - aNumber)
{
cout <<"I told you that you couldn't defeat me!\n\n";
cout <<"Now die!";
pLife = pLife - 1;
}
}
else if (rng == 3)
{
cout <<"What is " <<Number <<"+" << aNumber <<"?\n\n";
cin >> answer;
if (answer == Number + aNumber)
{
cout <<"What!!! How is that possible you deflected my attack!\n\n";
cout <<"Ahh it hit me!! you hit me with my own magic! Thats not fair!\n\n";
eLife = eLife- 1;
}
else if (answer > Number + aNumber, answer < Number + aNumber)
{
cout <<"I told you that you couldn't defeat me!\n\n";
cout <<"Now die!";
pLife = pLife - 1;
}
}
}while (eLife > 0, pLife > 0);
if (eLife == 0)
{
cout <<"Oh no! I cant belive it... you... actualy... defeated me?!\n\n";
cout <<"NO!!! CURSE YOU!!!";
cout <<"You've Won!\n\n";
system ("pause");
return 0;
}
else if (pLife == 0)
{
cout <<"MWAHAHAHAHAHA!!!!! I told you i would win!\n\n";
cout <<"Game over";
system ("pause");
return 0;
}
}
Each of the individual expressions in comma-separated expressions will be evaluated and their side effects will take place. However, the value of an entire comma-separated expression is only the result of the rightmost expression. Thus, the while condition evaluates as true only if pLife > 0 returns true.
To correct the problem, change it to a single expression using boolean operators such as && or ||