The result is not same as I expected - c++

The answer that I want should be 88.5 but it turns out to be 3.60434e+006. I think there's no problem with my quotient formula. What should I do?
#include <iostream>
using namespace std;
int main()
{
int Grade_one, Grade_two;
int Average = Grade_one+Grade_two;
double average = Average/2;
cout<<"Please input your Grade No.1: ";
cin>>Grade_one;
cout<<"Please input your Grade No.2: ";
cin>>Grade_two;
if (Grade_one == Grade_two){
cout<<"Your Grades are Same."<< endl;
}
if(Grade_one >= 50 && Grade_two >= 50 && Grade_one <= 74 && Grade_two <= 74){
cout<<"Hey! You should focus on your study, your grade is concerningly LOW."<< endl;
}
else if(Grade_one <= 49 && Grade_two <= 49){
cout<<"DUDE! you will fail for sure if you don't study."<< endl;
}
else if(Grade_one >= 75 && Grade_two >= 75 && Grade_one <= 100 && Grade_two <= 100){
cout<<average <<endl;
}
return 0;
}
"result"
Please input your Grade No.1: 88
Please input your Grade No.2: 89
3.60434e+006
Process returned 0 (0x0) execution time : 3.238 s
Press any key to continue.
The answer should be 88.5. How should I fix this?

Grade_one and Grade_two undefined when you first use them. You also need to cast Average to double if you want the result to be double as well.
#include <iostream>
using namespace std;
int main()
{
int Grade_one, Grade_two;
cout<<"Please input your Grade No.1: ";
cin>>Grade_one;
cout<<"Please input your Grade No.2: ";
cin>>Grade_two;
int Average = Grade_one+Grade_two;
double average = (double)Average/2;
if (Grade_one == Grade_two){
cout<<"Your Grades are Same."<< endl;
}
if(Grade_one >= 50 && Grade_two >= 50 && Grade_one <= 74 && Grade_two <= 74){
cout<<"Hey! You should focus on your study, your grade is concerningly LOW."<< endl;
}
else if(Grade_one <= 49 && Grade_two <= 49){
cout<<"DUDE! you will fail for sure if you don't study."<< endl;
}
else if(Grade_one >= 75 && Grade_two >= 75 && Grade_one <= 100 && Grade_two <= 100){
cout<<average <<endl;
}
return 0;
}

int Grade_one, Grade_two;
int Average = Grade_one+Grade_two;
Here, you read uninitialized variables. This is Undefined Behaviour and everything could happen: a crash, trash data, weird behaviour, ...
You need to delay the use of a variable only after you set it to a useful value, e.g.:
int Grade_one, Grade_two;
cout<<"Please input your Grade No.1: ";
cin>>Grade_one;
cout<<"Please input your Grade No.2: ";
cin>>Grade_two;
int Average = Grade_one+Grade_two;
double average = Average/2;

You are calculating average before Grade_one and Grade_two are initialized, that cannot work (it is undefined behavior). If you want to define something now and execute it later thats a function. You can use a lambda expression here. Average is a misnomer, it is a sum, not an average. You are using integer arithmetics for the division, but to get correct result it has to be calculated with floating points. I think you got the conditions for the if right, but the last case is simpler if you just make it an else without the condition. Last but not least, you should initialize variables always:
#include <iostream>
using namespace std;
int main()
{
int Grade_one = 0;
int Grade_two = 0;
auto average = [&](){
int Sum = Grade_one + Grade_two;
return Sum / 2.0;
};
Grade_one = 42;
Grade_two = 12;
if (Grade_one == Grade_two){
cout<<"Your Grades are Same."<< endl;
}
if(Grade_one >= 50 && Grade_two >= 50 && Grade_one <= 74 && Grade_two <= 74){
cout<<"Hey! You should focus on your study, your grade is concerningly LOW."<< endl;
}
else if(Grade_one <= 49 && Grade_two <= 49){
cout<<"DUDE! you will fail for sure if you don't study."<< endl;
}
else {
cout<<average() <<endl;
// ^^ call the lambda
}
return 0;
}

You need to modify your code slightly. Save this piece of universally useful code somewhere (preferably in a header file):
template <class Lam>
class Expr
{
public:
using ResultType = std::remove_reference_t<decltype((std::declval<Lam>())())>;
operator ResultType() { return lam(); }
ResultType value() { return lam(); }
Expr(Lam&& lam) : lam(std::move(lam)) {}
private:
Lam lam;
};
#define EXPR(...) Expr([&](){return (__VA_ARGS__) ;})
When you #include this piece in your program, you can proceed with minimal modifications:
int Grade_one, Grade_two;
auto Average = EXPR(Grade_one+Grade_two); // note the auto
auto average = EXPR(Average/2.0); // and the decimal point
I however strongly recommend exploring the other answers first.

Related

C++ coder for marks need help fixing it

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))"

Dynamic programming problem -Minimum Cost Path

I was trying this problem - Minimum Cost Path.
I have solved the problem using Dijkstra's Shortest Path Algorithm. But when i tried this using recursion+memoisation i.e. using dynamic programming, i got stuck and could not debug my code. I need help as to where my code is wrong!!
I am really glad for the help.
#include<bits/stdc++.h>
using namespace std;
int n;
int a[105][105], dp[105][105];
int dfs(int x, int y){
if(x < 0 || y < 0 || x >= n || y >= n){
return INT_MAX;
}
if(x == 0 && y== 0){
return a[0][0];
}
if(dp[x][y] != -1){
return dp[x][y];
}
dp[x][y] = a[x][y] + min(dfs(x-1, y), min(dfs(x, y-1), min(dfs(x+1, y), dfs(x, y+1))));
return dp[x][y];
}
int main(){
int tt;
cin >> tt;
while(tt--){
int n;
cin >> n;
for(int i = 0 ; i < n; i++){
for(int j = 0; j < n; j++){
cin >> a[i][j];
dp[i][j] = -1;
}
}
cout << dfs(n-1, n-1) << endl;
}
return 0;
}
Example:
Input:
2
5
31 100 65 12 18 10 13 47 157 6 100 113 174 11 33 88 124 41 20 140 99 32 111 41 20
2
42 93 7 14
Output:
327
63
I am getting 2147483647 as the output for both the cases, which is the value of INT_MAX.
The global variable n that dfs looks at is always zero (by static initialization), it's never assigned a value. When main calls, say, dfs(4, 4), the function immediately returns INT_MAX due to 4 >= 0 check.
Once you fix this simple issue, you'll discover that your program crashes due to stack overflow. You see, dfs(4, 4) calls dfs(3, 4), which in turn calls dfs(4, 4), which calls dfs(3, 4), which ...
This is not really a dynamic programming problem. It's a "shortest path in a graph" problem, suitable for, say, Dijkstra or A* algorithms.

highest cf between 2 numbers c++

This is a program to find highest common factor:
#include <iostream>
enter code here using namespace std;
void main ()
{
int max=0 , min=0 , x,y,hcf=0;
cout<<"enter 2 numbers\n";
cin>>x>>y;
if (x>y)
{
max=x;
min=y;
}
else if (y>x)
{
max=y;
min=x;
}
if
(max%min==0)
{ hcf=min;
cout<<"highest cf is:"<<hcf<<endl;}
else
{
hcf=min;
do
{
hcf--;
}
while (max%hcf!=0 && min%hcf!=0);
cout<<"highest cf is:"<<hcf<<endl;
}
system ("pause");
}
although when i test it ; it takes the condition max% hcf !=0 and ignores the second one ... for example if i input 12 and 8 then 12 is called max and 8 is min then it outputs 6 as hcf
that means it ignored the second condition ... as i understand of course.
so where is my mistake ?
A easy solution to get the HCF is to do this.
int HCF(int num1, int num2)
{
for(int i = num1; i > 2; i++)
{
if(num1 % i == 0 && num2 % i == 0) return i;
}
return 1;
}

How do I stop these if else statements from compounding?

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).

What does it mean if a "variable or field" is declared void? Error message help

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.