Error while multiplying decimals with variables in C++ - c++

I'm a student and started learning C++ recently.I was making a GPA calculator for my juniors in C++ but I'm facing an error. When I multiply a decimal with a variable, I get the same answer every time. This happens with the decimals only. Exact integers work fine.
I get the right answer if I place the value of variable "cal" in the range of and integer.Like if I place 85, I get 12 as output but when I type the value below 85, I get 3.1 every time.
Can you point out my mistake?
Here is my starting source code :
#include <iostream>
#include <string>
using namespace std;
int main()
{double cal,calh,c1;
cout<< "How many marks you obtained in calculus? \n";
cin >>cal;
cout<<"Enter the credit hours of Calculus? \n";
cin>>calh;
if (cal>85 || cal==85){c1=4*calh;}
else if (cal>80 || cal==80 || cal<85){c1=3.7*calh;}
else if (cal>75 || cal==75 || cal<80){c1=3.3*calh;}
else if (cal>70 || cal==70 || cal<75){c1=3*calh;}
else if (cal>65 || cal==65 || cal<70){c1=2.7*calh;}
else if (cal>61 || cal==61 || cal<65){c1=2.3*calh;}
else if (cal>58 || cal==58 || cal<61){c1=2*calh;}
else if (cal>55 || cal==55 || cal<58){c1=1.7*calh;}
else if (cal>50 || cal==50 || cal<55){c1=1*calh;}
else if (cal<50 || cal==49){cout<<"Sorry but you are failed in calculus.";}
cout<<"your total gpa in calculus is "<< c1<<endl;
system("pause");
return 0;
}

Think about what you wrote
else if (cal>80 || cal==80 || cal<85){c1=3.7*calh;}
This will match everything (any number is either larger than 80 or less than 85)
You want something like this instead
#include <iostream>
#include <string>
using namespace std;
int main()
{
double cal, calh, c1;
cout << "How many marks you obtained in calculus? \n";
cin >> cal;
cout << "Enter the credit hours of Calculus? \n";
cin >> calh;
if (cal >= 85) { c1 = 4 * calh; }
else if (cal >= 80) { c1 = 3.7*calh; }
else if (cal >= 75) { c1 = 3.3*calh; }
else if (cal >= 70) { c1 = 3 * calh; }
else if (cal >= 65) { c1 = 2.7*calh; }
else if (cal >= 61) { c1 = 2.3*calh; }
else if (cal >= 58) { c1 = 2 * calh; }
else if (cal >= 55) { c1 = 1.7*calh; }
else if (cal >= 50) { c1 = 1 * calh; }
else { cout << "Sorry but you are failed in calculus."; c1 = 0; }
cout << "your total gpa in calculus is " << c1 << endl;
system("pause");
return 0;
}

Let's look at your first two conditional lines:
if (cal>85 || cal==85){c1=4*calh;}
else if (cal>80 || cal==80 || cal<85){c1=3.7*calh;}
In the second one, you are entering in the condition for every possible value, as you are asking "any value that are greater than 80, but also any value that are lower than 85". So you will always have c1 = 3.7*calh, except if cal is superior to 85. That's why you are getting the same value everytime.
I think the problem is that you misunderstood the logic of the || operator. When you have several conditions in a if statement separated with a ||, it means that only one of the conditions needs to be true to enter the condition. If you want to keep this logic, remove the "==" and ">" tests and replace them with a ">=" one, and replace your || operator with &&.
Now let's look at your code again. There is some conditions you are repeating there. You already that you are entering the first else if cal is lesser than 85, so you don't need to verify it again. Then, in the end, you can replace
else if (cal>80 || cal==80 || cal<85){c1=3.7*calh;}
With:
else if(cal >=80) {c1=3.7*calh;}
Apply this trick everywhere, and you are done.

Related

Password requirements

I'm trying to declare this string as Invalid but in an input like this:
59G71341 or 8pjf7h14sx13 or 60s1v344
My output is getting approved through my string if statement and is getting listed as Valid.
Could anyone guide me to why its passing through my if statement and labeling Valid!!
I haven't learned how to use a debugger yet so bare with me.
Task description:
Declare a Boolean variable named goodPasswd. Use goodPasswd to output "Valid" if secretStr contains no more than 5 digits and secretStr's length is greater than or equal to 5, and "Invalid" otherwise.
Ex: If the input is 80796, then the output is:
Valid
Ex: If the input is XBdg, then the output is:
Invalid
#include <iostream>
using namespace std;
int main()
{
string secretStr;
bool goodPasswd = false;
cin >> secretStr;
int counter = 0;
for (int i = 0; i < secretStr.length(); ++i)
{
if ((secretStr[i] >= 0) && (secretStr[i] <= 9))
{
++counter;
}
} //approves string if both true
if ((counter <= 5) && (secretStr.length() >= 5))
{
goodPasswd = true;
}
else
{
goodPasswd = false;
}
if (goodPasswd)
{
cout << "Valid" << endl;
}
else
{
cout << "Invalid" << endl;
}
return 0;
}
if ((secretStr[i] >= 0) && (secretStr[i] <= 9))
should be
if ((secretStr[i] >= '0') && (secretStr[i] <= '9'))
0 and 9 are integers, but you are comparing characters, so you need to use the characters '0' and '9', or you could just use the isdigit function.
if (isdigit(secretStr[i]))
isdigit is declared in #include <cctype>
Not related to your question but you don't need to goodPasswd variable. Simply
if (counter <= 5 && secretStr.length() >= 5)
{
cout << "Valid" << endl;
}
else
{
cout << "Invalid" << endl;
}
seems a bit cleaner to me.

C++ Blackjack code only going to first if statement

I'm trying to code a blackjack game and everything is going smoothly so far but for this bit. No matter what I input into hitStand it always goes to the first if statement and "hits". I would like for if "h" is inputted it "Hits" and if "s" is inputted it "Stands" and, if there is an invalid input, it will tell the user to try again.
I'm still fairly new to C++, so some help would be appreciated.
while (repeat == 0)
{
char hitStand;
cout << "Would you like to HIT or STAND [H/S]";
cin >> hitStand;
if (hitStand = "H" || "h")
{
PcardNew = rand() % 13 + 1;
cout << endl;
cout << "Your new card is: " << PcardNew << endl;
if (PcardNew > 10)
{
PcardNew = 10;
}
playerTotal = playerTotal + PcardNew;
cout << "Your new total is: " << playerTotal << endl;
}
else if (hitStand = "S" || "s")
{
break;
}
else
{
cout << "Please enter a valid imput [H/S]" << endl;
}
}
There are (at least) three errors in the single if (hitStand = "H" || "h") line!
First, the = operator is an assignment, not a comparison; to test for the equality of two operands, you need the == operator.
Second, the "H" and "h" constants are string literals - that is, multi-character, null-terminated strings of characters. Use single quotes for single characters (thus, 'H' and 'h').
Third, you can't compare one object with two others like that with a logical or (||) operator. You need to make two separate comparisons and then or the results of each:
So, use this:
if (hitStand == 'H' || hitStand == 'h')
{
//...
And similarly for your second test:
else if (hitStand == 'S' || hitStand == 's')
{
//...
That is because your condition in if statement is always true. Since "h" is in or (||).
Instead use:
if (hitStand == 'H' || hitStand == 'h')
and
else if (hitStand == 'S' || hitStand =='s')

I need help solve my problem of my activity

So I need my help to correct my code, which is given to my programming class assignment. My activity is to print numbers divisible by 5 for the integers from 1 to 99. So I tried to code like this:
#include <iostream>
using namespace std;
int main () {
int num, min, max;
cout << "Enter Number: ";
cin >> num;
min = 1;
max = 99;
if (num > min || num < max) {
if (num % 5 == 0) {
cout << "Divisible.";}
else {
cout << "Not Divisible";}
}
else {
if (num % 5 == 0) {
cout << "Error Input.";}
else {
cout << "Error input.";}
}
return 0;
}
So when I compile and run, I test to enter a divisible number by 5 or not. When I put 0, it says "Error input," that's correct. However, when I put 100, it says "divisible" instead of "error input." What is the correct input of my code?
The input is an integer from 1 to 99, which means that it should be >= 1 AND <= 99.
So, simply change
if (num > min || num < max)
to
if (num >= min && num <= max)
You made a mistake in the first if statement. When you are giving the OR operator, it'll return true even if only one of the conditions are satisfied.
You should use the AND operator for your code to work as expected.
Moreover, you don't have to use the min and max variables also, it is making the program unnecessarily big (only 2 lines though, but still).

C++ Tennis Score Tracker

Taking an intro to C++ class in University and we got this project to 'model' a tennis game.
The user will first need to enter the probability that player a will win.
Then generate a number between 1 and 100 until a player has more than 4 points and has 2 more points than the other player.
My problem is that sometimes around the 50% win rate area the output will come out as 4-4.
I am wondering why this is happening?
Any help would be greatly appreciated!!
int prob;
int scoreA = 0;
int scoreB = 0;
int randNB = 0;
srand(time(NULL));
cout <<"---------------\n"
"FAKE TENNIS!\n"
"---------------" <<endl;
cout <<"What is the chance that player \'A\' will win a point?(Enter whole #between 1 - 100): " ;
cin >> prob;
do{
if((scoreA >= 4 || scoreB >= 4) && ((scoreA - scoreB) >= 2 || (scoreB - scoreA) >= 2)) break;
randNB = rand()%100+1;
if (randNB <= prob){
cout<<"A";
scoreA++;
}
else if(randNB > prob){
cout<<"B";
scoreB++;
}
}
while((scoreA <= 3|| scoreB <= 3) && ((scoreA - scoreB) !=2 || (scoreB - scoreA) !=2 ));
cout<<"The final score is " <<scoreA <<" (A) - " << scoreB <<" (B)" <<endl;
if(scoreA > scoreB){
cout <<"A is the winner!!!";
}
else{
cout <<"B is the winner!!!";
}
return 0;
}
You've written the end-loop test twice.
Once as a positive inside the loop (correctly) and once as a negative at the end of the loop.
1) Write it only once. (The "break" will end the loop.) That is, replace the do { ... } while(...) with just while(true) { ... }
2) If you want to write it twice, check <2 rather than != 2 in the second test. The negation of x>=2 is not x!=2

Cannot be used as a function?

For some reason my met variable cannot be used as a function in my last while statement, even though my other two variables can be. When i compile I get the error: '(met <= 2.0e+1)' cannot be used as a function|. How do i fix this?
// Garbage Collection. Michael Heusner.
#include <iostream>
#include <cmath>
using namespace std;
int main(){
int reg_lim, met_lim, glass_lim;
double reg, glass, met;
double total;
double reg_ratio, glass_ratio, met_ratio;
reg_lim= 50;
glass_lim= 20;
met_lim= 20;
cout << "How much regular, glass, and metal garbage do you have?" << endl;
cin>> reg;
cin>> glass;
cin>> met;
total= met+glass+reg;
cout<< "The total number of bags is "<< total<< endl;
met_ratio= met/total;
reg_ratio= reg/total;
glass_ratio= glass/total;
cout<< "The metal ratio is "<< met_ratio<< endl;
cout<< "The glass ratio is "<< glass_ratio<< endl;
cout<< "The regular ratio is "<< reg_ratio<< endl;
if( met==reg==glass)
{
cout<< "All garbage amounts are the same."<< endl;
}
else if (reg> glass && met)
{
cout<< "Regular is the largest."<< endl;
}
else if (glass> met && reg)
{
cout<< "Glass is the largest."<< endl;
}
else if (met> glass && reg)
{
cout<< "Metal is the largest."<< endl;
}
while( reg <= 50) (met <= 20) (glass <= 20);{
while( reg <= 50) (met <= 20) (glass <= 20);{
would be your problem!
That is not a valid while loop statement.
Instead, you should write:
while (( reg <= 50) && (met <= 20) && (glass <= 20)) {
//Statements for loop
}
You may want to balance some parentheses and add some logical operators in that while() condition. Once you do that, perhaps losing the semi-colon before the opening brace will actually break the infinite loop you're about to start executing with the appropriate values for reg, met, and glass.
while (( reg <= 50) && (met <= 20) && (glass <= 20))
{
}
You'll need to use && to chain together your conditions:
while ((reg <= 50) && (met <= 20) && (glass <= 20))
You have a similar problem in your earlier if statement:
if( met==reg==glass)
This should be:
if ((met==reg) && (reg==glass))
But since these are floating point numbers, you should instead check that they differ only by a minimum difference.