I was trying to learn c++ i wanted to find marks using the code the issue is that it is not giving me the correct output and i wanted it to loop if the marks are less i wawnted to repeat it .
This is the code that i wrote
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
void mygrade(int grades)
{
if (grades >= 90)
{
printf("High distinction");
}
else if (grades > 80 < 70)
{
printf("Your Grade is Distinciton");
}
else if (grades > 60 < 70)
{
printf("Credit");
}
else if (grades > 50 < 60)
{
printf("Pass");
}
else if (grades < 50)
{
printf("Fail");
}
else
{
printf("Enter vaild Marks");
}
}
void main()
{
int grades;
printf("Enter your score for this unit\n");
scanf("%d", &grades);
printf("your grade for this unit is: %d ");
}
If you want the program work as you write in the picture, there are three things to do:
You can just use
if (grades >= 90)
// …
else if (grades >=80)
// …
// and so on
since else if statement will be trigger only if all cases above it are not true.
You need to call mygrade() function in the main() function so that it will run.
If you want to repeat the program if the grades are less than 50, then you can use do-while loop.
do
{
//…
}while (grades < 50);
Your mistake is to use comparisons like "(grades > 80 < 70)", which is not allowed in C++. Replace them with the form "((grades > 70) && (grades < 80))"
Related
I am making a C++ code where you will create an array using a do while loop.
Here is the full code:
const int size = 10;
double *pt1;
//executable
pt1=new double[size];
int i = 0;
do{
cout <<"mile" << "[" << i << "]" << setw(3);
if(*(pt1+i) >= 100 && *(pt1+i) <= 250)
{
cin >> *(pt1+i);
i++;
}
else if( *(pt1+i) > 100 && *(pt1+i) < 250)
{
cout << "100-250 only";
continue;
}
}while(i < 10);
There is an input validation where the numbers that will be accepted are only numbers from 100 to 250 but it keeps on looping. I can't find where the problem is. Any help would be greatly appreciated!
The first error is that you are testing the value of the input before you actually get the input. That makes no sense, you need to switch the order around. So this
if(*(pt1+i) >= 100 && *(pt1+i) <= 250)
{
cin >> *(pt1+i);
...
}
else if( *(pt1+i) > 100 && *(pt1+i) < 250)
{
...
}
should be this
cin >> *(pt1+i);
if(*(pt1+i) >= 100 && *(pt1+i) <= 250)
{
...
}
else if( *(pt1+i) > 100 && *(pt1+i) < 250)
{
...
}
Secondly I think you meant
else if( *(pt1+i) < 100 || *(pt1+i) > 250)
Or better you could have just said
else
Then there is no chance of getting the logic wrong. When you have only two choices, you just need to test for the first choice and use else for the second choice. There's no need to test for the opposite of the first choice, using a plain else will do that automatically.
Also continue at the end of a loop is not necessary, loops continue automatically.
Finally pt1[i] is much easier to read than *(pt1+i).
I'm trying to write a c++ program that reads input from a text file and assigns grades using a ten point grading scale then prints the results onscreen.
I think my issue may be with the if else statements in the function deriveGrade, rather than incrementing the enum, they seem to be suming up the increments. Any help would be appreciated, thanks.
#include <iostream>
#include <string>
#include <iomanip>
#include <cmath>
#include <fstream>
using namespace std;
int deriveGrade(double avarage);
enum letter_grade { A, B, C, D, F };
namespace tenPoint
{
letter_grade deriveGrade(double avarage);
char grade;
}
using namespace tenPoint;
int main()
{
string name;
double average;
ifstream inData; // Is the variable for input data from the file.
inData.open("student_status.txt", ios::in);
while (!inData.eof())
{
getline(inData, name);
inData >> average;
inData.ignore();
grade = ::deriveGrade(average);
cout << name << " " << average << " " << char(grade) << endl;
}
inData.close();
return 0;
}
int deriveGrade(double average)
{
if (average >= 90)
{
grade = static_cast<letter_grade>(grade + 65);
}
else if (average >= 80 && average < 90)
{
grade = static_cast<letter_grade>(grade + 1);
}
else if (average >= 70 && average < 80)
{
grade = static_cast<letter_grade>(grade + 2);
}
else if (average >= 60 && average < 70)
{
grade = static_cast<letter_grade>(grade + 3);
}
else if (average <= 50)
{
grade = static_cast<letter_grade>(grade + 4);
}
else
{
cout << "Invalid entry." << endl;
}
return grade;
}
Input from file:
Doe, John K.
93.2
Andrews, Susan S.
84.7
Monroe, Marylin
75.1
Gaston, Arthur C.
62.8
Harpo, Joanie Y.
42.7
Ginger, Fred T.
95.8
Program output:
Doe, John K. 93.2 A
Andrews, Susan S. 84.7 B
Monroe, Marylin 75.1 D
Gaston, Arthur C. 62.8 G
Harpo, Joanie Y. 42.7 K
Ginger, Fred T. 95.8 î
Press any key to continue . . .
Logic of your program is quite strange, but some common remarks can be given without deepening into your task.
Pay attention, that while you use if... else statements one by one like
if (average >= 90)
{
grade = static_cast<letter_grade>(grade + 65);
}
else if (average >= 80 && average < 90)
{
grade = static_cast<letter_grade>(grade + 1);
}
...
there is no need to check average < 90 in the else branch after average >= 90 found false. So at least code can be shorter:
int deriveGrade(double average)
{
if (average >= 90)
{
grade = static_cast<letter_grade>(grade + 65);
}
else if (average >= 80)
{
grade = static_cast<letter_grade>(grade + 1);
}
else if (average >= 70)
{
grade = static_cast<letter_grade>(grade + 2);
}
else if (average >= 60)
{
grade = static_cast<letter_grade>(grade + 3);
}
else if (average <= 50)
{
grade = static_cast<letter_grade>(grade + 4);
}
else // check here! Invalid interval is for values between 50 and 60?
{
cout << "Invalid entry." << endl;
}
return grade;
}
But this is not significant improvement.... much better to make a formula and use single statement with assignment to grade = ...
UPDATE:
And one more comment. If you know the interval of unacceptable values, check it first (before all other calculations):
int deriveGrade(double average)
{
// check the correctness of argument first
if (average > 50 && average < 60)
{
cout << "Invalid entry." << endl; // notification
return grade; // previous value
// also consider returning special value for error case
}
// calculate value for grade
grade = ...
// return updated value
return grade;
}
section "calculate value for grade" is for you, and while writing this part of code keep in mind that:
ternary operation operation is useful for one special case, e.g. grade = (average >= 90)? 65 : floor(100 - average) / 10;
using global values (like grade) in a function is bad practice as well as making logic based on the assumption that initial value of global variable is correct
The reason is because you are adding to your grade variable without clearing it, so the result of previous operations are carried over in deriveGrade.
My advice is to remove the global char grade; in your namespace, use a local variable in your deriveGrade, and a different local variable in your main.
If you look at your function code, grade will only have 65 added to it (to make an ASCII 'A') if your grade is above 90. Every subsequent addition however, pretends that this addition has happened. If you instead make sure that each else if does not rely on previous if or else if code, then your code should be more correct.
char deriveGrade( double average )
if( average > 90.0 )
{
return 'A';
}
else if( average > 80.0 )
{
return 'B';
}
...
This solution removes even the need to use a grade variable in your deriveGrade
An even better alternative that uses the enum you so nicely created is:
enum letter_grade : char
{
A = 'A', B = 'B', C = 'C', D = 'D', F = 'F'
};
Which allows you through a (char)letter_grade to swap between the enum representation and a char (your deriveGrade would then return a letter_grade instead).
#include <iostream>
#include <windows.h>
#include <cstdlib>
#include <stdlib.h>
using namespace std;
int main()
{
int x,y,z;
cout<<"welcome to guessing game\nplayer one pick your number: ";
cin>>x;
if (x < 0)(x > 100);
{
cout<<"out of number range";
}
Sleep(2000);
system("cls");
cout<<"ok player 2 pick the guess";
cin>>y;
if (x == y){
cout<<"congrats you got it right";
}
else{
if (x < y){
cout<<"Go lower";}
else {
if (x > y){
cout<<"higher";}}
}
system("pause>nul");
return 0;
}
i cant see the get the initial if statement to work no matter what number i type in it would auto display the out of number range. also am i allowed to place the conditions like that soo close like if (x < 0)(x > 100);. also how do i make it soo it returns to the start of the program?
There is an error:
if (x < 0)(x > 100);
{
cout<<"out of number range";
}
Should be:
if (x < 0 || x > 100)
{
cout<<"out of number range";
}
You also need to work on your indentation; those if/else statements towards the bottom look dodgy (I cannot really tell due to the indentation).
Aside from writing if (x < 0 || x > 100) (and dropping the semicolon), you should be wary of comparing equality on floating point. I would red flag your line if (x == y){ if reviewing your code.
See Floating point comparison
nobody else is actually answering your second question: how to loop it, here you go:
int x;
cout << "Welcome to the guessing game\n";
do {
cout << "Please enter a number from 0 to 100: ";
cin >> x;
} while (x < 0 || x > 100);
You have written
if (x < 0)(x > 100);
{
cout<<"out of number range";
}
First remove the semi colon.
Second did you mean
if ((x < 0) || (x > 100))
{
cout<<"out of number range";
}
try this:
/*
if (x < 0)(x > 100);
{
cout<<"out of number range";
}
*/
if (x < 0 || x > 100)
{
cout<<"out of number range";
}
There are a few notable syntax errors:
if (x < 0)(x > 100);
{
cout<<"out of number range";
}
First of all, you can't just put two conditions side by side like that in C++ that I know of. You'd have to separate them with || for OR, or && for AND (in most cases - there are some others).
Also, you had a ; at the end of your if statement. I believe that doing this in C++ will result in some problems too.
Your final code should look like:
if ((x < 0) || (x > 100))
{
cout << "out of number range" << endl;
}
The << endl; part is optional. This adds a new line to your output, for more readability next time you write something.
Also, to loop your entire game repeatedly, I would use a do-while loop. You can learn about them here.
Heres my code im trying to get tidied up for school, in the embedded if and else if statements it show errors when I try to compile.
errors : expect primary-expression before "else"
expected ';' before else
both of these come up for each line.
// This is a program to Calculate the volume of the sphere using the radius (a03.cpp)
// Written by: Jimmy Scott
// Date: 2/1/12
// Sources: Stackoverflow.com (else and if statements)
#include <iomanip>
#include <iostream>
#include <string>
using namespace std;
int main ()
{
char vehicle;
float total;
char over20;
char old;
int adults;
int oldpass;
char height;
int youngpass;
int bicycles;
float length;
cout<<"Fare Calculator by Jimmy Scott";
cout<<"\n\n\n Are You Bringing a vehicle on The Ferry ?";
cin>>vehicle;
if (vehicle == 'y')
{
cout<<"\n\n"<<"Is the Driver over 65 Years of age or disabled?";
cin>>old;
cout<<"\n\n"<<"Passengers going along with the driver"<<"\n\n";
cout<<"Adults (19-64 Years old):";
cin>>adults;
cout<<"\n\n"<<"Senior Citizens or disabled:";
cin>>oldpass;
cout<<"\n\n"<<"Young passengers 5-18 years old: ";
cin>>youngpass;
cout<<"\n\n"<<"Is your Vehicle over 7ft, 6in in height? ";
cin>>height;
cout<<"Vehicle length in feet: ";
cin>>length;
if (old == 'y')
{
total= 44.60;
}
else if (old == 'n');
{
total= 51.20;
}
else if (length < 20) and (height == 'y');
{
total= 102.4;
}
else if (length > 20) and (length < 30);
{
total= 76.80;
}
else if (length > 20) and (length < 30) and (height = 'y');
{
total= 153.60;
}
else if (length > 30) and (length < 40);
{
total= 204.80;
}
}
else
{
cout<<"\n\n"<<"How many Senior Citizens or disabled are in your group?";
cin>>oldpass;
cout<<"\n\n"<<"How many adults are in your group?:";
cin>>adults;
cout<<"\n\n"<<"How many in your group are youths (5-18):";
cin>>youngpass;
cout<<"\n\n"<<"How many in your group have Bicycles:";
cin>>bicycles;
total=oldpass * 6.55;
total= total + (adults * 13.15);
total= total + (youngpass * 10.55);
total= total + (bicycles * 4.00);
}
cout<<"\n\n"<<"your total fare cost is : $"<<total;
cout<<"\n\n\n"<<"Press <Enter> to Exit";
cin.ignore();
cin.get();
return 0;
}
Several things:
When you do a conditional, don't follow the test directly with a semicolon, as this stops the conditional statement and will do something different from what you want. Furthermore, since it terminates the if-else group, you will generate an error on the next 'else' statement.
You also need to enclose your conditional tests with parenthesis.
Here is an example of a correct else if statement:
else if ((length > 30) and (length < 40))
{
total= 204.80;
}
Update: I initially said to use && instead of 'and'. As honk says 'and' is a valid operator in c++ that does the same thing as &&. I prefer to use && for portability with c though.
eliminate all the ';' after the if else() statements. Also add '( )' if you make many conditions.
variable or field `letterGrade' declared void. This error message is coming up on the last iteration of the function 'letterGrade'. Anyone have an idea why?
#include <string>
#include <iostream>
using namespace std;
void letterGrade (int score, string& scoreLetter);
string scoreLetter;
int main()
{
int score;
char A, B, C, D, F;
cout<<"Enter the grade: ";
cin>> score;
letterGrade (score, scoreLetter);
cout<<"The letter grade is a(n) "<< scoreLetter<<".";
system ("pause");
return 0;
}
void letterGrade (score, scoreLetter)
{
for (score >= 90)
{
scoreLetter = 'A';}
if (score == 100)
{
scoreLetter.insert (1, "+");
}
else if (8<=score% 10 && score% 10 <= 9)
{
scoreLetter.insert (1, "+");
else if (0<=score% 10 && score% 10 <=1)
{
scoreLetter.insert (1, "-");
}
You aren't naming the types on the parameters of the definition of letterGrade.
void letterGrade (score, scoreLetter)
{
//...
In the function definition above, you forgot to specify the types. Mention the types as:
void letterGrade (int score, std::string & scoreLetter)
{ // ^^^this ^^^^^^^^^^^^^this
//...
Don't forget to #include<string>.
Another problem is this:
for (score >= 90)
The form of for should be this:
for(initialization; condition ; increment/decrement/changing-some-value)
Example:
for ( int i = 0 ; i <= score ; i++)
First of all, as the others said - fix the letterGrade definition:
vvv vvvvvvvvvvvv
void letterGrade( int score, std::string& scoreLetter )
After that, fix the for, it should be something like:
for (; score >= 90; --score )
{
//..
}
Also, note that you shadow the global scoreLetter in letterGrade
Are you actually looping in the letterGrade function?
Most homework assignments like this only require an if-then-elseif-else ladder.
I suggest removing the for statement and replacing with an if statement. If you decide you need to loop or repeat, restore the for statement.
A for loop would allow you to traverse a table of scores vs. grade strings:
struct Grade_Score
{
unsigned int grade;
const char * grade_text;
};
const Grade_Score grade_table[] =
{
{100, "A+"},
{90, "A"},
{80, "B"},
{70, "C"},
{60, "D"}
};
const unsigned int NUM_GRADE_ENTRIES =
sizeof(grade_table) / sizeof(grade_table[0]);
std::string Grade_To_Score(unsigned int grade)
{
std::string score = "F";
for (i = 0; i < NUM_GRADE_ENTRIES; ++i)
{
if (grade >= grade_table[i].grade)
{
score = grade_table[i].grade_text;
break;
}
}
return score;
}
A similar search can be performed using the std::lower_bound or std::upper_bound functions.
Edit 1:
I suggest you replace system("pause"); with something more portable like:
cout << "Press Enter to continue\n";
cout.ignore(10000, '\n');
Not all platforms support the pause command.
IIRC for can be written with only the comparison, aka end condition, specified
for (a>b)
for (a=2; a>b)
for (a>b; a++)
Should all work providing we do the missing initialization or iterator elsewhere in the code.