C++ expected primary-expression before ';' token - c++

I get an error message that states "expected primary-expression ';' token" and it highlights my percentage formula. I have tried to rearrange my code, but it seems the problem is not in it.
const int TOTALSUITES = 120;
for (int floor = 10; floor <= 16; floor++) {
if ( floor != 13) {
do {
cout << "Please enter the number of suites occupied on the floor " << floor << ":";
cin >> numOccupied;
if ((numOccupied <0) || (numOccupied >20 )) {
goodChoice = false;
cout << "\n\t\t**ERROR" << numOccupied << " ***\n\n";
cout << "*** Choice must be from [0-20]***\n";
}
else {
goodChoice = true;
}
totalOccupied += numOccupied;
} while (!goodChoice);
}
}
percentage = (totalOccupied / TOTALSUITES) * 100% ;
cout << endl;
cout << "Hotel has " << TOTALSUITES << endl;
cout << "Number of occupied suites is " << totalOccupied << endl;
cout << "The percentage of occupied suites is " << percentage << endl;
system("pause");
return 0;

% used here is the modulo operator which is a binary operator...
so this is what you have to do...
percentage = (totalOccupied / TOTALSUITES)* 100;
//and then where you have cout percentage at that point...do this
cout<<"the percentage of occupied suites is"<<percentage<<"%";

100% is not 100 percent. 100% is trying to use the % operator in an incorrect manner. To multiply by 100% you just use 1 which is not needed as anything times 1 is itself.

percentage = (totalOccupied / TOTALSUITES) * 100% ;
This is not valid syntax. Change it to this.
percentage = (totalOccupied / TOTALSUITES);
Assuming your totalOccupied is not a float, you should probably do this as well:
percentage = (static_cast<float>(totalOccupied) / TOTALSUITES);

% is actually the modulus operator in C++, requiring two arguments.
100% is therefore not syntactically valid.
Assuming that you want % to stand-in for a "divide by 100" operator, the simplest thing to do in your case is to drop the 100% from your code.
Note that totalOccupied / TOTALSUITES will be carried out in integer arithmetic if totalOccupied is also an int or unsigned. Fix that by promoting one of the arguments to a double, or pre-multiply the term with 1.0.

Related

invalid operands of types 'int' and 'const char [11]' to binary 'operator<<'

First of all, I'm just a beginner so I'm sorry if this would sound really stupid.
I'm currently doing a game in C++ where every move of a player corresponds to additional money and time deduction. Each player starts with 0 initial money and 30 minutes of time. I plan to have this on loop until both players have 0 time remaining.
This is part of my code:
if ((groupNumber1 == 1))
{
cout<<"You now have a total of "<<"$"<< initialMoney += teensMoney <<" and have "<< initialTime -= teensTime <<" minutes remaining."<<endl;
}
else if ((groupNumber1 == 2))
{
cout<<"You now have a total of "<<"$"<< initialMoney += familyMoney <<" and have "<<initialTime -= familyTime <<" minutes remaining."<<endl;
}
Now when I run the program it gives me this:
[Error] invalid operands of types 'int' and 'const char [11]' to binary 'operator<<'
May I know where is the error?
Thank you so so much!
Looks like a precedence problem. += will come AFTER <<
initialMoney += teensMoney --> ( initialMoney += teensMoney )
Because of operator precedence rules (<< is evaluated before += and -=), you need to bracket your arithmetic expressions, like this:
if ((groupNumber1 == 1))
{
cout<<"You now have a total of "<<"$"<< (initialMoney += teensMoney) <<" and have "<< (initialTime -= teensTime) <<" minutes remaining."<<endl;
}
else if ((groupNumber1 == 2))
{
cout<<"You now have a total of "<<"$"<< (initialMoney += familyMoney) <<" and have "<<(initialTime -= familyTime) <<" minutes remaining."<<endl;
}
Echoing #user4581301's point - are you sure you want to use += and -= here? That will permanently change the values stored in those variables after the printout, which I doubt is what you want to do. That would also not print out the correct values - do you see why?
Instead, just use good old fashioned + and -:
if (groupNumber1 == 1)
{
cout << "You now have a total of " << "$" << initialMoney + teensMoney << " and have " << initialTime - teensTime << " minutes remaining." << endl;
}
else if (groupNumber1 == 2)
{
cout << "You now have a total of " << "$" << initialMoney + familyMoney << " and have " << initialTime - familyTime << " minutes remaining." << endl;
}
Simplifying the problem to reduce the noise we get
cout << a += b << endl;
Due to operator precedence, this is interpreted by the compiler as
(cout << a) += (b << endl);
and the b << endl stage makes no sense. You can fix this by forcing the order you want with brackets
cout << (a += b) << endl;
But I find modifying values inside output statements leads to programming mistakes because, even if you intend to update a with +=, folks expect values to come and go from an output statement unchanged. If you really want to update the value of a, I would remove all ambiguity with
a+=b;
cout << a << endl;
If you don't mean to update a
cout << a + b << endl;

Is there a way to print the sum of randomly generated numbers in a do while loop?

I am writing a program to very fundamentally simulate a black jack game using rand() % 11. We have to tell the players their running total as well as asking if they want another card (hit). My first problem is getting multiple random numbers and my second problem is not being able to add the two random numbers together. Strings are not allowed. Here's the block of code that I think is causing there's errors. I am very new to c++. Do I need to have multiple variables with the rand() %10 +1 to add them? I know that the add + add won't work but I can't figure out an alternative.
int add = rand() % 10 + 1;
bool hit = false;
int i = 0;
do {
cout << "Players 1 running total is " << add;
i++;
cout << " \n ";
cout << "Would you like another number? (0-yes or 1-no) ";
cin >> hit;
if ( hit == 0 ) {
cout << " You got an " << add << " \n ";
cout << "You're running total is " << add + add;
}
} while ( hit == false );
I assume this is an assignment given by an educator, otherwise, you shouldn't be using rand() at all (I don't blame you, I blame the instructor for not keeping up with the language.)
You must call rand() again to get a new number and use another variable to store the total:
Sidenote:
You should really declare your variables as close to first use as possible instead of the top of the program.
Also, The variable i isn't being used in this context so I removed it.
srand(time(0)); //Should be nullptr, but instructor probably doesn't know that.
int total = 0;
bool hit = false;
do {
int add = rand() % 10 + 1;
total += add;
cout << "\nYou got an " << add << " \n ";
cout << "\nPlayer 1 running total is " << total;
cout << "\nWould you like another number? (0-yes or 1-no) ";
cin >> hit;
} while (hit == false);
cout << "Player 1 final total is: " << total << endl;

I am debugging this C++ program. There are no more syntax errors that compiler shows, but there are hidden logical errors

#include <iostream>
#include <iomanip>
using namespace std;
const int N = 20;
int main ()
{
//Declare variables
int counter; //loop control variable
int number; //variable to store the new number
int zeros = 0; //Step 1
int odds = 0; //Step 1
int evens = 0; //Step 1
int positives = 0;
int negatives = 0;
// Display Program Intro telling what the program does.
cout << "********************************************************"
<< "\n* This is a program that counts integers you enter as *"
<< "\n* even, odd or zero and positve or negative *"
<< "\n* It classifies 20 numbers or use 99999 to exit early *"
<< "\n********************************************************"
<< endl;
// Ask for 20 integers with 99999 as early exit
cout << "\n\nPlease enter " << N << " integers, "
<< "positive, negative, or zeros."
<< "\n\t\t or enter number 99999 to exit early. \n\n"
<< endl; //Step 2
cout << "The numbers you entered are:" << endl;
// Loop that classifies the numbers entered.
for (counter = 1; counter <= N; counter++) //Step 3
{
// Enter number and mirror it backed on a tabbed line.
cin >> number; //Step 3a
cout << number << endl; //Step 3b
// Early exit condition: 99999
if(number = 99999)
break; // Exit loop before 20 numbers
// Count Postive and Negative Numbers
if(number < 0)
negatives++;
else
positives++;
// Count Evens, Odds and Zeros
//Step 3c
switch (number % 2)
{
case 0:
evens++;
if (number == 0)
zeros++;
case 1:
case -1:
odds++;
} //end switch
} //end for loop
cout << endl;
// Display the results ....
//Step 4
cout << "There are " << evens << " evens, "
<< "which includes " << zeros << " zeros."
<< endl;
cout << "The number of odd numbers is: " << odds
<< endl;
cout << "The number of positive numbers is: " << positives
<< endl;
cout << "The number of negative numbers is: " << negatives
<< endl;
// Use Holdscreen to make sure the results are visible ....
char holdscr; // This character and section is to hold screen open
cout << "\n\n\tPress a character and Enter to exit program. ";
cin >> holdscr;
return 0;
}
I am debugging this program. There were originally 6 errors in the program. I've found four of them as they were syntax errors. The compiler doesn't show any error but the program isn't working either.
The program is supposed to store 20 numbers and in the end tell you how many of them were even, odd, zero, negative, and positive. I am just a beginner in C++. I have tried every possible way to solve it from my side but I cannot get it to work. I have looked up every code and syntax on Google why it works that way but found no help. Any help here would be highly appreciated.
If you enable warnings when you compile then the compiler will helpfully point out certain mistakes in your code, and if it's in a good mood it may even suggest a solution:
<stdin>:46:23: warning: using the result of an assignment as a condition without parentheses [-Wparentheses]
if(number = 99999)
~~~~~~~^~~~~~~
<stdin>:46:23: note: place parentheses around the assignment to silence this warning
if(number = 99999)
^
( )
<stdin>:46:23: note: use '==' to turn this assignment into an equality comparison
if(number = 99999)
^
Always compile with warnings enabled (e.g. gcc -Wall ...) - it will save you a lot of time and debugging effort in the long run.

Uninitialized local variable that is actually initialized? [duplicate]

This question already has answers here:
How can I declare and define multiple variables in one line using C++?
(10 answers)
Comma as separator in variable initialization (not as operator)
(2 answers)
How does the Comma Operator work
(9 answers)
Closed 1 year ago.
I am writing a program that deals with values in an input file. My variables include total, taxtotal, subtotal, etc. & they have already been declared and initialized, yet I am getting two error messages: "uninitialized local variable 'subtotal' used" and the same for the variable "taxtotal".
Here is my source code:
#include "stdafx.h"
#include<stdio.h>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
ifstream shoppingBasketFile;
shoppingBasketFile.open("HW3_Data.txt");
bool isTaxed = false;
char taxValue = 0;
char inPrice[64];
char name[128];
double price, taxtotal, subtotal, total = 0;
if (shoppingBasketFile.is_open())
{
// display the header info:
cout << "o Thank you for shopping at StuffMart" << endl;
cout << setw(3) << left << "o "
<< setw(20) << left << "Item"
<< setw(12) << "Unit Price"
<< setw(4) << "Tax"
<< endl
<< "o -------------------------------------" << endl;
// parse the input file until end of file;
while (!shoppingBasketFile.eof())
{
// parse the item name:
shoppingBasketFile >> name;
cout << "Name = " << name << endl;
if (name == NULL)
{
// what should we really do here?
continue;
}
// parse the price:
shoppingBasketFile >> price;
if (price < 0 || price > 100000000000) {
continue;
}
cout << "Price = " << price << endl;
// parse the isTax flag:
shoppingBasketFile >> isTaxed;
shoppingBasketFile >> taxValue;
cout << "Is taxed? = " << taxValue << endl;
// if end of file break out of this loop:
if (!shoppingBasketFile.good()) break;
if (isTaxed == true) {
taxtotal = taxtotal + (.085 * price);
taxValue = 'Y';
}
else {
taxValue = 'N';
}
//display tax as Y instead of T/1
if (isTaxed == true) {
cout << "Tax: Y" << endl;
}
else {
cout << "Tax: N" << endl;
}
//compute the subtotals
subtotal = subtotal + price;
// display the item info:
cout << "name" << name << ", price: $" << price << ", is taxed: " << taxValue << endl;
// reset input values:
name, price, isTaxed = 0;
// end of while loop
}
//compute the final total:
total = subtotal + taxtotal;
//output the totals
cout << "o" << setw(37) << "---------------" << endl
<< "o " << setw(26) << "Subtotal $" << fixed << setprecision(2) << right << subtotal << endl
<< "o " << setw(26) << "Tax (8.5%) $" << fixed << setprecision(2) << right << taxtotal << endl
<< "o " << setw(26) << "Total $" << fixed << setprecision(2) << right << total << endl;
}
shoppingBasketFile.close();
return 0;
}
How can I eliminate these error messages? I am using Microsoft's Visual C++ compiler, if that matters.
In this declaration:
double price, taxtotal, subtotal, total = 0;
the type name double applies to all 4 variables, but the = 0 initialization applies only to total.
As others have said, the most direct fix is:
double price = 0, taxtotal= 0, subtotal = 0, total = 0;
but it's better style to declare each variable on its own line:
double price = 0.0;
double taxtotal = 0.0;
double subtotal = 0.0;
double total = 0.0;
Note that using 0 is perfectly valid (the int value will be implicitly converted to the double value 0.0), but using a floating-point constant is more explicit.
(I've chosen to align the initializers vertically. Some might prefer not to do that.)
I'm guessing you haven't gotten to pointers yet. When you do, you'll encounter another reason to declare each variable on its own line. This:
int* x, y, z;
defines x as an int*, but y and z as int. Using one declaration per line, as for the initializers above, avoids this opportunity for error and confusion:
int* x;
int* y;
int* z;
Once you get your code to compile, you'll have a problem with this line:
name, price, isTaxed = 0;
That's a valid statement, but it doesn't do what you think it does.
, is the comma operator. It evaluates its left and right operands in order, and yields the value of the right operand, discarding the value of the left operand. The statement evaluates and discards the current value of name, then evaluates and discards the current value of price, then assigns the value 0 to isTaxed. (Thanks to user4581301 for pointing this out.)
You could write this as:
name = price = isTaxed = 0;
(since an assignment yields the value that was assigned) or, more simply, as:
// name = 0;
price = 0.0
isTaxed = false;
I've commented out the assignment to name, since it's an array and you cannot assign a value to an array object. I won't show a corrected version because I don't know what you're trying to do here.
Suggestion: Start small, keep it simple, and confirm at each step that your code works before adding new code. I think you've tried to write too much code at once. You have nearly 100 lines of code that won't even compile. I've been programming for a long time and I wouldn't write that much code without making sure it compiles and runs.
It looks like you declared subtotal in your statement here:
double price, taxtotal, subtotal, total = 0;
but only initialized total with value 0, causing its use on the right side of the assignment to trigger the error:
subtotal = subtotal + price;
To initialize multiple items simply add the "=" explicitly.
Example:
double price = 0, taxtotal = 0, subtotal = 0, total = 0;

Division producing only integers C++

I use rand function to generate two random numbers, numerator and denominator, that are used in division, sometimes the result is float and sometimes is integer. How can I generate only an integer result ? here is my code :
srand(time(NULL));
integer1 = ((rand() % ( 81 - 5 ) + 5 )*2);
integer2 = ((rand()%3 + 1)*2);
answer = integer1/integer2;
do {
cout << "How much is " << integer1 << " divided by " << integer2 << " ? : " << endl;
cin >> answer;
if (answer == integer1/integer2) {
cout << "Very Good !"<< endl;
}
else {
cout << "Your answer is false, please try again !"<<endl;
}
} while ((integer1/integer2!=answer));
If both operands of / are integral types, the result will be integral. If either operand is a floating point type the result will be a floating point type. If you want it to be a truncated integer you'll need to cast to the type you desire.