Conditonals using c++ - c++

I am coding a simple speeding ticket program and I got it to compile but I am having problems getting it to read my conditions and execute the final part of the program which is calculating the ticket.
#include <iostream>
using namespace std;
int main()
{
int speedTraveled;
int speedLimit = 55;
int mischiefSpeed = 75;
int criminalSpeed = 110;
cout << "How fast were you going? " << "\n";
cin >> speedTraveled;
if (speedTraveled >= 0 || speedTraveled >= 150)
{
if (speedTraveled > speedLimit && speedTraveled > mischiefSpeed)
{
int tFormula = ((speedTraveled - speedLimit) * 2) + 50;
cout << "You were speed bettween 55mph - 75mph your fine is : ", tFormula, '\n';
}
else if (speedTraveled > mischiefSpeed && speedTraveled < 110)
{
int tFormula = ((speedTraveled - speedLimit) * 5) + 50;
cout << "Your speed was over 75 mph but less than 110 mph your are being arrested : ", tFormula, '\n';
}
else if (speedTraveled >= criminalSpeed)
{
int tFormula = ((speedTraveled - speedLimit) * 2) + 50;
cout << "You were speed over 110 mph your are being arrested : ", tFormula, '\n';
}
}
return 0;
}

I tested using the value 150. The first if statement executes because you did not set an upper bound on it. Try setting the second > into a <. Same thing with the first if statement
if (speedTraveled >= 0 || speedTraveled >= 150) // No upper bound
if (speedTraveled >= 0 || speedTraveled <= 150) // Upper bound is 150
The fine amounts are not printing because you need an insertion operator (<<) between the different data types you are trying to output. cout uses syntax different from output functions in other languages.
cout << "You were speed between 55mph - 75mph your fine is : ", tFormula, '\n';
cout << "You were speed between 55mph - 75mph your fine is : " << tFormula << endl;
You have more if statement typos, but I'm sure you can find the rest.

Related

why does my code not read or follow the if statements?

Why does my code not read or follow the if statements?
#include<iostream>
using namespace std;
int main (){
int sum = 0;
int integer;
while ((integer != -1) && (sum < 2000)){
int integer;
cout<<"Enter an integer: ";
cin>>integer;
if (integer == -1){
cout<<"Program was terminated.\n"<<"Your total sales are: "<<sum<<endl;
break;
}
else if (sum >= 2000) {
cout<<"Congratulations!"<<"Your total sales are: "<<sum<<endl;
break;
}
sum = sum + integer;
if (sum > 499){
cout<<"You're off to a good start!"<<endl;
}
if (sum > 999){
cout<<"You're halfway through!"<<endl;
}
else if (sum > 1499){
cout<<"You're almost there!"<<endl;
}
}
return 0;
}
Expected:
Input looks like:
Enter an interger: 350, 500,800, 500
Then the out should look like:
Enter an integer 350
" " 500
youre off to a good start
800
youre halfway through
500
Congratualations! Youre total sales are: 2150
Reality:
Enter an integer: 350
Enter an integer: 500
You're off to a good start!
Enter an integer: 800
You're off to a good start!
You're halfway through!
Enter an integer: 500
You're off to a good start!
You're halfway through!
you want only 1 branch to be entered, so you need a if else if chain.
if (sum >= 2000) {
std::cout << "Congratulations!" << "Your total sales are: " << sum << std::endl;
break;
}
else if (sum > 1499) {
std::cout << "You're almost there!" << std::endl;
}
else if (sum > 999) {
std::cout << "You're halfway through!" << std::endl;
}
else if (sum > 499) {
std::cout << "You're off to a good start!" << std::endl;
}
You have to start with the largest number to the smallest one, since if you go from smaller to larger, if a branch is entered it will always be the first branch.
while ((integer != -1) && (sum < 2000)){
this is wrong, as integer is not initialiazed and this is therefore undefined behaviour. In some cases it might never enter the while loop because integer holds some random garbage value that happens to be -1.
You can replace it with a simple while true loop:
while (true) {
since you are calling break; in the final branches anyway (this escapes the while loop). This will also fix the bug, that the loop would terminate before the final print outs.
int integer;
while ((integer != -1) && (sum < 2000)) {
int integer;
you just declared integer twice, the second one is not needed.
Full code:
#include <iostream>
int main() {
int sum = 0;
int integer;
while (true) {
std::cout << "Enter an integer: ";
std::cin >> integer;
if (integer == -1) {
std::cout << "Program was terminated.\n" << "Your total sales are: " << sum << std::endl;
break;
}
sum = sum + integer;
if (sum >= 2000) {
std::cout << "Congratulations!" << "Your total sales are: " << sum << std::endl;
break;
}
else if (sum > 1499) {
std::cout << "You're almost there!" << std::endl;
}
else if (sum > 999) {
std::cout << "You're halfway through!" << std::endl;
}
else if (sum > 499) {
std::cout << "You're off to a good start!" << std::endl;
}
}
}
read Why is "using namespace std;" considered bad practice?

Program goes into infinite loop when trying to make it guess a random number it selected?

This is an assignment for class. I am trying to get it to generate a random number and guess what it generated. I am still new in learning c++.I understand that it has to update a variable whenever it iterates but i don't know how to update the variable in the loop. Where am i going wrong?
using namespace std;
int main()
{
srand(static_cast<unsigned int>(time(0))); //seed random number generator
int actual = rand() % 64 + 1; //random number betweeb 1 and 64
int tries = 0;
int searchGridHighNumber = 64;
int searchGridLowNumber = 1;
int targetLocationPrediction = ((searchGridHighNumber - searchGridLowNumber) / 2) + searchGridLowNumber;
cout << "Generate Random enemy location on 8x8 grid....\n";
cout << "The enemy is located at location #" << actual << " on 8x8 grid
with 1
- 64 sectors.\n ";
cout
<< "Skynet HK -Aerial Initializing software.....";
do {
++tries;
if (targetLocationPrediction > actual) {
cout << "Skynet HK-Aerial rader sending out ping #" << tries
<< endl;
cout << "the target location prediction of" << targetLocationPrediction << "was higher than the actual enemy location of"
<< actual << endl;
"\n";
int targetLocationPrediction = searchGridHighNumber;
}
else if (targetLocationPrediction < actual) {
cout << "Skynet HK-Aerial rader sending out ping #" << tries << endl;
cout << "the target location prediction of" << targetLocationPrediction << "was lower than the actual enemy location of" << actual << endl;
int targetLocationPrediction = searchGridLowNumber;
}
else {
cout << "enemy was hiding at location #" << actual << endl;
cout << "Target was found at location #" << targetLocationPrediction << endl;
cout << "Skynet HK-Aerial Software took" << tries << "predictions to find the enemy location on a grid size of 8x8(64)";
cout << "Press any key to continue...";
}
} while (targetLocationPrediction != actual);
return 0;
}
Removing all the unnecessary fiction (it's a good idea to solve the problem before adding fancy output), you have
int guess = ((high - low) / 2) + low;
do {
if (guess > actual) {
int guess = high;
}
else if (guess < actual) {
int guess = low;
}
} while (guess != actual);
which makes it clearer that you declare new variables when the guess is wrong.
This means that the actual guess is never modified and the loop never terminates, so remove the int:
int guess = ((high - low) / 2) + low;
do {
if (guess > actual) {
guess = high;
}
else if (guess < actual) {
guess = low;
}
} while (guess != actual);
The next problem is that you never shrink the guessing interval – if the guess is too low the next one will be 1; if it's too high the next one will be 64.
Another non-terminating loop, unless the target is 32.
You need to
Shrink the interval; the new top is guess - 1 or the new bottom is guess + 1.
Make a new guess in the middle of the new interval.
It's easier to compute the guess at the beginning of the loop, as you only need to it in one place:
do {
int guess = ((high - low) / 2) + low;
if (guess > actual) {
high = guess - 1;
}
else if (guess < actual) {
low = guess + 1;
}
} while (guess != actual);
It seems to me as if you are reassigning the variable to one of two variables. The only way the loop would end is if the actual variable was 1 or 64.
What you want to do is create a random number and guess it right? Well do that then. In this program, I update the variable only when the user gets the number correct. I didn't set up any if statements/loops to check for answers over or below the max and minimum values.
#include <iostream>
#include <time>
using namespace std;
int main()
{
int actualGuess;
bool tries = false;
srand(static_cast<unsigned int>(time(0))); //seed random number generator
int actual = rand() % 64 + 1;
//Create the random variable value, and create another random value and guess it.
//use the sleep function because if you call rand() during the same second, it will give you the same value.
//Or you can simply use a user entered variable to compare to the 'actual' value
cout << "Skynet HK -Aerial Initializing software....." << endl;
do{
cout << "What is the correct number?" << endl;
cin> actualGuess;
if(actual == actualGuess){
cout << "Correct!" << endl;
tries = true;;
}
if(actual != actualGuess){
cout << "Incorrect!" << endl;}
}while(tries = false);
return 0;
}
This is some pseudocode for your code. The code below is not compilable, it is designed to understand the flow of your program.
H_Num = 64;
L_Num = 1;
actual = 23 //say actual rands to 23
TargLoc = ((H_Num - L_Num) / 2 + L_Num)
TargLoc = (64 - 1 )/ 2 + 1)
TargLoc = 63/2 + 1
TargLoc = 32; //This is what would happen, given the variables you initialized.
tries = 1
if TargLoc > actual
cout - 1
cout - 32
TargLoc = 64
else if
cout 1
cout 32 - 23
TargLoc = 1
else
cout - 23
cout - 64
cout - 1
cout

|| operator in while condition not working as expected

So I'm a new programmer and I decided to try and make this game. It is a basic, let's say person v. person game. You enter the amount of each team, in my case Ninjas and Samurai, and then it randomizes the attack chance of each and outputs the winner. Every time I run the program I input the number of each type, and I always get an output of the Ninjas having 0 health, and the Samurai having negative health. How would I be able to have the while loop end when one team gets to 0 health? I've tried using totalNinjaHealth != 0 || totalSamuraiHealth != 0 but the program runs infinitely.
#include <iostream>
#include <random>
#include <string>
#include <ctime>
using namespace std;
int main() {
int ninjas;
int NINJA_HEALTH = 2;
int NINJA_ATTACK = 2;
int samurai;
int SAMURAI_HEALTH = 3;
int SAMURAI_ATTACK = 1;
default_random_engine randomGen(time(NULL));
uniform_real_distribution<float> attackChance(0.0f, 1.0f);
cout << " *** Ninjas V Samurai *** " << endl;
cout << "Input amount of Ninjas" << endl;
cin >> ninjas;
cout << "Input amount of Samurai" << endl;
cin >> samurai;
int totalNinjaHealth = NINJA_HEALTH * ninjas;
int totalSamuraiHealth = SAMURAI_HEALTH * samurai;
cout << totalNinjaHealth << endl;
while (totalNinjaHealth > 0 == true || totalSamuraiHealth > 0 == true)
{
if (attackChance(randomGen) > 0.5f) {
totalSamuraiHealth -= NINJA_ATTACK;
cout << totalSamuraiHealth << endl;
}
else if(attackChance(randomGen) < 0.5f) {
totalNinjaHealth -= SAMURAI_ATTACK;
cout << totalNinjaHealth << endl;
}
}
if (totalNinjaHealth == 0) {
cout << "Ninjas lost all " << ninjas << " Ninjas. Samurai remaining " << totalSamuraiHealth << endl;
}
else if (totalSamuraiHealth == 0)
{
cout << "Samurai lost all " << ninjas << " Samurai. Ninjas that remain " << totalNinjaHealth / 2 << endl;
}
cin.get();
cin.get();
return 0;
}
Screenshot of what happens when ran:ConsoleWhenRan
Am I using the || operator incorrectly? I thought the || operator waits until one condition is true and then stops, but when I run the code It seems to wait until both either pass, or equal 0 giving the negative output.
You need to use the && operator. The || is the "or" operator and will evaluate to true when either one or both of the conditions are true. In your case, the while loop will continue to evaluate as long as one of your teams has health > 0. The "and" operator (&&) requires both conditions to be true for the statement to be evaluated as true.
What happens is:
You run the loop until either of the teams has positive total health. So the total health is for both of the teams is less/equal to zero.
Then you check the healths and you get your answer. It just so happens that in your case one of the teams died with exactly 0 health. In some cases though, the output should show neither the messages.

Generating numbers outside of my range C++ (way too large)

I decided for fun to try and make a simple program that "sort of" simulates blackjack in a dumbed down way. It's basically done, except for the fact that the randomly generated numbers are WAY too large. I don't care about the bias srand/rand has (for now) I just want to get it working properly.
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <ctime>
using namespace std;
int genRandInt (int low, int high) {
int randnum = low + (rand() % (high - low + 1));
return randnum;
}
int main()
{
srand(time(NULL));
int computerScore;
int score;
int card;
while (int playAgain = 1)
{
cout << "Enter 0 to hold or 1 to hit: ";
int play;
cin >> play;
if (play == 0)
{
computerScore = genRandInt(1, 31);
if (score < computerScore)
{
cout << "Your score is " << score << " and the computer's score is " << computerScore << "! You lose.\n";
}
if (score > 21)
{
cout << "Your score is " << score << " which is greater than 21. Bust!\n";
}
if (score > computerScore && score <= 21)
{
cout << "Your score is " << score << " and the computer's score is " << computerScore << "! You win!\n";
}
cout << "Would you like to play again? 1 for yes, 0 for no. : ";
cin >> playAgain;
}
if (play == 1)
{
card = genRandInt(1, 11);
score = score + card;
cout << "Your score is: " << score << "\n";
}
}
return 0;
}
Any ideas?
You use int score; uninitialized in
if (score < computerScore)
or
score = score + card;
depending on the if(play == 0) or if(play == 1) condition.
It happens to have some junk as its memory content, the compiler does not initializes to zero for you. In fact, it is undefined behaviour to use un-initialized variables. Initialize it before the first usage, preferable in the definition itself,
int score = 0;
Also, compile with warnings on (-Wall -Wextra for g++/clang++), since the compiler will easily warn about these mistakes.
Try running this and seeing if you have the same issues. I just added some print statements to try and debug it, and it stopped showing me really big numbers..
EDIT:
//ADD
int score = 0;
//
if (play == 1)
{
cout << "printing in the PLAY = 1 "<< score << endl;
card = genRandInt(1, 11);
score = score + card;
cout << "Your score is: " << score << "\n";
}

Having trouble cout-ing returned functions

I am new to C++ and am having trouble passing string back to the main class of my code.
My goal is to split the below code so that I have 2 functions other than the main class and at least one must return a value other than 0.
Beginning code:
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
cout.precision(2);
cout.setf(ios::fixed,ios::floatfield);
float speedLimit;
float driversSpeed;
float ticketAmount;
float speedOver;
string repeat;
/*Use a symbolic constant for the base ticket fine rate ($50).*/
const float base = 50;
start:
/*Prompt the user for the speed limit and the speed of the driver.*/
cout << "Enter the speed limit: ";
cin >> speedLimit;
cout << "Enter the driver's speed: ";
cin >> driversSpeed;
cout << "You were driving " << driversSpeed << " in a " << speedLimit << " mph zone.\n";
speedOver = driversSpeed - speedLimit;
if (speedOver <= 10 && speedOver >= 1)
{
ticketAmount = base;
}
else if (speedOver <= 14 && speedOver >= 11)
{
ticketAmount = (base *.05) + base;
}
else if (speedOver <= 19 && speedOver >= 15)
{
ticketAmount = (base *.1) + base;
}
else if (speedOver <= 24 && speedOver >= 20)
{
ticketAmount = (base *.15) + base;
}
else if (speedOver <= 29 && speedOver >= 25)
{
ticketAmount = (base *.2) + base;
}
else if (speedOver >= 30)
{
ticketAmount = (base *.25) + base;
}
else
{
ticketAmount = 0;
}
cout << "Your fine is $" << ticketAmount;
cout << "\nEnter Y to continue. Anything else to stop: ";
cin >> repeat;
if (repeat == "Y" || "y")
goto start;
else
exit(0);
return 0;
}
and here what I have done so far:
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
const float base = 50;
float speedLimit;
float driversSpeed;
float ticketAmount;
float speedOver;
int _tmain(int argc, _TCHAR* argv[])
{
cout.precision(2);
cout.setf(ios::fixed,ios::floatfield);
string repeat;
/*Use a symbolic constant for the base ticket fine rate ($50).*/
start:
/*Prompt the user for the speed limit and the speed of the driver.*/
cout << "Enter the speed limit: ";
cin >> speedLimit;
cout << "Enter the driver's speed: ";
cin >> driversSpeed;
/*Display to the user the values which were input (speed limit and driver's speed) and the calculated ticket fine amount. Print 2 numbers after the decimal point for the fine amount. Make sure your output format matches the sample format.*/
cout << "You were driving " << driversSpeed << " in a " << speedLimit << " mph zone.\n";
speedOver = driversSpeed - speedLimit;
cout << string(finalOutput);
/*After the fine is printed for the first speeding violation, prompt the user to see if he/she wants to enter another speeding violation. If so, prompt again for the speed limit and driver's speed. Repeat the calculation and print the fine. Repeat this process until the user indicates he/she wants to stop. The user can enter either an uppercase or lowercase letter Y to continue with the program.*/
cout << "\nEnter Y to continue. Anything else to stop: ";
cin >> string(repeat);
if (repeat == "Y" || "y")
goto start;
else
exit(0);
}
float ticketAmountFunc(float ticketAmount)
{
/*Calculate the ticket cost as $50 (the base fine rate) plus:
0% additional if the driver's speed was 10 or less miles per hour above the speed limit.
5% additional if driver's speed was more than 10 miles per hour above the speed limit.
10% additional if driver's speed was more than 15 miles per hour above the speed limit
15% additional if driver's speed was more than 20 miles per hour above the speed limit.
20% additional if driver's speed was more than 25 miles per hour above the speed limit.
25% additional if driver's speed was 30 or more miles per hour above the speed limit.
Do not charge a fine if the driver wasn't speeding.*/
if (speedOver <= 10 && speedOver >= 1)
{
ticketAmount = base;
}
else if (speedOver <= 14 && speedOver >= 11)
{
ticketAmount = (base *.05) + base;
}
else if (speedOver <= 19 && speedOver >= 15)
{
ticketAmount = (base *.1) + base;
}
else if (speedOver <= 24 && speedOver >= 20)
{
ticketAmount = (base *.15) + base;
}
else if (speedOver <= 29 && speedOver >= 25)
{
ticketAmount = (base *.2) + base;
}
else if (speedOver >= 30)
{
ticketAmount = (base *.25) + base;
}
else
{
ticketAmount = 0;
}
return ticketAmount;
}
string finalOutput(string tix)
{
string words = "Your fine is $";
//tix = words + ticketAmountFunc;
tix += string(words) + string(ticketAmountFunc);
return tix;
}
VS is returning 2 errors:
Error 1 error C2065: 'finalOutput' : undeclared identifier
Error 7 error C2440: '<function-style-cast>' : cannot convert from 'float (__cdecl *)(f
loat)' to 'std::string'
Could someone please poing me in the direction of my error?
Thank you.
EDIT: Thank you Ben. I moved my main method and tried moving variables around to declare them as strings and still have the undeclared identifier issue but now twice.
Here is my updated code:
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
const float base = 50;
float speedLimit;
float driversSpeed;
float ticketAmount;
float speedOver;
string ticketAmountFunc(string r)
{
string ticketAmount;
if (speedOver <= 10 && speedOver >= 1)
{
ticketAmount = base;
}
else if (speedOver <= 14 && speedOver >= 11)
{
ticketAmount = (base *.05) + base;
}
else if (speedOver <= 19 && speedOver >= 15)
{
ticketAmount = (base *.1) + base;
}
else if (speedOver <= 24 && speedOver >= 20)
{
ticketAmount = (base *.15) + base;
}
else if (speedOver <= 29 && speedOver >= 25)
{
ticketAmount = (base *.2) + base;
}
else if (speedOver >= 30)
{
ticketAmount = (base *.25) + base;
}
else
{
ticketAmount = "0";
}
std::string s = ticketAmount;
r = s;
return r;
}
string finalOutput(string tix)
{
string words = "Your fine is $";
//tix = words + ticketAmountFunc;
tix = string() + words + ticketAmountFunc(r);
return tix;
}
int _tmain(int argc, _TCHAR* argv[])
{
cout.precision(2);
cout.setf(ios::fixed,ios::floatfield);
string repeat;
/*Use a symbolic constant for the base ticket fine rate ($50).*/
start:
/*Prompt the user for the speed limit and the speed of the driver.*/
cout << "Enter the speed limit: ";
cin >> speedLimit;
cout << "Enter the driver's speed: ";
cin >> driversSpeed;
cout << "You were driving " << driversSpeed << " in a " << speedLimit << " mph zone.\n";
speedOver = driversSpeed - speedLimit;
cout << string(finalOutput(tix));
cout << "\nEnter Y to continue. Anything else to stop: ";
cin >> string(repeat);
if (repeat == "Y" || "y")
goto start;
else
exit(0);
}
and my errors are:
Error 7 error C2065: 'r' : undeclared identifier
Error 8 error C2065: 'tix' : undeclared identifier
You're trying to use the functions before their "point of declaration". There are two simple solutions (pick one):
Add a forward declaration aka prototype before you use it.
Move the caller (main()) below the functions it uses.
Also, when calling a function, you need to provide its arguments inside parentheses. So you need to say ticketAmountFunc(ticketAmount) and not just ticketAmountFunc.
In addition to these problems, you seem to be defining function parameters as the value the function generates, instead of the data it uses. That's not useful. When you use functions well, you won't need global variables.
If I could just add, try to avoid using goto statements at this stage in your career - make use of proper loops and functions instead.
This is not a blanket rule, but goto's can be avoided unless there are very specific & valid reasons.
You could use loops like this:
bool Quit = false;
while(!Quit) {
// user wants to quit
Quit = true; // execution continues after end of while loop
}
Also make use of the toupper function, google "C++ toupper" so that you don't have to do 2 test on the value of the char.
If you can, avoid using namespace std as it pollutes the gloabal namespace which can cause conflict with function & variable names. For example the STL has all kinds of common words like distance, left & right etc which have special meaning. So either put std:: before each std thing, or do this for frequently used things:
using std::cout;
using std::cin;
using std::endl;
using std::string;
Some guys use std:: exclusivley, while I sometimes do a mixture of these two ideas.
Hope all goes well.