Cannot be used as a function? - c++

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.

Related

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

C++ do while loop not working

I'm trying to make this code work:
#include <iostream>
using namespace std;
int main()
{
int i;
do
{
cout << ("please enter a number between 1 and 10");
cin >> i;
} while(i > 10 && i < 1)
cout << "the square of the number you have entered is " << i*i;
}
Basically, the idea is that a user enters a number between 1 and 10. While the number is not between 1 and 10, it keeps asking the user to enter a number between the values. Then, when the number is between the values, it is squared and returned to the user.
I can't see why this isn't working
Any help is appreciated
You have:
while (i > 10 && i < 1)
You want:
while (i > 10 || i < 1)
while (i > 10 && i < 1)
Your condition is logically faulty; if reinterpreted, it says:
while i is greater than 10 AND i is less than 1
Judging from your code, the || operator should be used:
} while (i > 10 || i < 1);
As others mentioned, your condition is faulty.
a number can't obviously be under 1 AND above 10 at the same time, so the while loop exits immediately after the do statement.
#include <iostream>
using namespace std;
int main()
{
int i;
do
{
cout << ("please enter a number between 1 and 10");
cin >> i;
} while (i < 1 || i > 10)
cout << "the square of the number you have entered is " << i*i;
}
You should use an Or ||, that condition with && will never be true.
The loop condition is wrong and will never loop, as i cannot be less than 1 && greater than 10 at the same time. You should use the logical OR (||) operator instead. In addition, there must be a semicolon placed after the do-while statement. And you probably want and end of line placed after the prompt. Also, you don't want to start the bad habit of polluting the global namespace, even with the awesomeness of std. So:
#include <iostream>
int main()
{
int i;
do {
std::cout << "please enter a number between 1 and 10\n";
std::cin >> i;
} while (i > 10 || i < 1);
std::cout << "the square of the number you have entered is " << i*i << std::endl;
}

Error while multiplying decimals with variables in 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.

Simple C++ input files and if statements

I wrote the code and it works except the total is wrong. It is supposed to multiply the distanceRate by the rate and add each cost to make the total, but it's not doing that. Any help would be appreciated.
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
using namespace std;
int main()
{
//Declare Variables
ifstream inFile;
double packageWeight;
double distance;
double totalCharge = 0;
double rate;
double distanceRate;
int customerNumber;
double shippingCharge;
int packageCount = 0;
inFile.open("shipping.txt");
if(inFile)
{
cout << "Customer Package Shipping" << endl;
cout << "Number Weight Distance" << endl;
while(!inFile.eof())
{
inFile >> customerNumber;
inFile >> packageWeight;
inFile >> distance;
if(0 < packageWeight <= 2)
rate = 1.10;
else if(2 < packageWeight <=6)
rate = 2.20;
else if(6 < packageWeight <= 10)
rate = 3.70;
else if(10 < packageWeight <=20)
rate = 4.80;
else
cout << "Invalid package weight" << endl;
if( 0 < distance <= 500)
distanceRate = 1;
else if( 500 < distance <= 1000)
distanceRate = 2;
else if(1000 < distance <= 1500)
distanceRate = 3;
else if(1500 < distance <= 2000)
distanceRate = 4;
else
cout << "Invalid distance" << endl;
packageCount += customerNumber;
shippingCharge = rate * distanceRate;
totalCharge += shippingCharge;
cout << fixed << setprecision(2) << showpoint;
cout << setw(2) << customerNumber
<< right << setw(14) << packageWeight
<< setw(13) << distance
<< endl;
} //End of while loop
cout << "\nPackage shipped : " << packageCount << endl;
cout << "Total Charge : $" << totalCharge << endl;
inFile.close();
}
else
{
cout << "Could not open file" << endl;
}
system("pause");
return 0;
}
Some issues that I see in the snippet you gave me are as follows:
As pointed out by billz in a comment, your if statements are invalid. The statement if( 0 < distance <= 500) is not doing what you expect, it evaluates from left to right, so you have 0 < distance (lets say that evaluates to true) so then you have true <= 1000 which isn't going to give the results that you think it will. This actually needs to be broken apart into two separate comparisons like distance > 0 && distance < 500.
As I noted in my comment, you're adding the customer number to the package count, this will most likely always give a wrong value for package count. If your customer numbers are 1, 2, 3, 4 then you claim the package count is 10 when it's actually only 4 (forgive me if I misunderstood the purpose of this field).
You have no default value for distanceRate but you still use it in an operation (possibly uninitialized) which will give unexpected results (as you are seeing). In your else, you should actually give it a dummy value that way you guarantee that it will always be set. You also do reset it, so if it gets set to 4, and then next distance fails the tests and enters the else, you have another calculation on the variable as 4 instead of it's default value. You should initialize any variable that you plan to use unless you have explicit reason not to give it a value at initialization, and anytime you use a variable in a loop you should reset it's value at the start of the loop.
Additional Note (EDIT)
I wouldn't recommend using system("pause"); as it does a lot more behind the scenes than you would want in a simple pause, a better approach I've seen used is:
#include <iostream>
#include <conio.h>
using namespace std;
int main() {
cout << "Press any key to continue!";
_getch();
cout << "Finished";
return 0;
}
EDIT 2
If statments can contain a single line or a code block to execute.
Single line:
if (someValueIsTrue)
executeThisFunction();
Code block:
if (someValueIsTrue) {
executeThisFunction();
alsoThisFunction();
}
Anytime you need to execute more than one statement in an if/else/while/for/do...while/etc... you'll need a code block. I imagine (based on your explanation) that you did:
if (blah)
// ....
else
distanceRate = 0;
cout << "Invalid Distance";
And the compiler only sees that you have the distanceRate = 0 nested in the loop, the cout statement is actually not part of the else but part of the previous block of code. You need to use a code block here.
!inFile.eof() // incorrect
inFile.good() // correct
read on eof() it doesn't do what you might think it does.
if( 0 < distance <= 500) // all the if statements are incorrect
if(distance>0 && distance<=500) // correct
The way you wrote the if condition, it does not do what you think it does.