How do I prevent this loop? C++ - c++

I'm new to C++ and stack overflow in general so please excuse me if a make a mistake somewhere.
I posted my code down below, but my issue is that when I type either yes or no at after the calculation is complete, no is supposed to end the program (which I was still working on) and yes is supposed to set it up for another calculation.
However I end up with a glitchy loop.
#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
bool b;
bool yes = b;
do {
float x;
float y;
float z;
float a;
cout << "Enter The amount you are investing:" << endl;
cin >> x;
cout << "Enter the rate:" << endl;
cin >> y;
cout << "Enter the investment period (years):" << endl;
cin >> z;
cout << "Enter the compounding period:" << endl;
cin >> a;
cout << pow((1 + y / a), (a*z))*x << endl << "Want to do another? (yes/no)";
cin >> b;
cin.ignore();
} while (yes = true); {
cin.clear();
if (b = yes) {
}
else {
}
}
return 0;
}

The behaviour of your code is probably due to:
unintentional reassignment of the termination condition bool value: yes to: true, instead of checking its value, which is done with ==, not with the assignment =.
no modification of the value yes within the while loop.
A possible update is:
#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
// initialise the sentinel
bool yes = true;
do {
// define variables
float x, y, z, a;
// read input
cout << "Enter The amount you are investing:" << endl;
cin >> x;
cout << "Enter the rate:" << endl;
cin >> y;
cout << "Enter the investment period (years):" << endl;
cin >> z;
cout << "Enter the compounding period:" << endl;
cin >> a;
cout << pow((1 + y / a), a * z) * x << endl;
// redo calculation or exit
cout << "Want to do another? (yes/no)";
cin >> yes;
// check termination condition
} while (yes == true);
return 0;
}
Additionally, watch out for the uninitialised variables: x, y, z, a and think for a proper default value that will indicate possible wrong result.
Lastly, withing the calculation: 1 + y / a is ambiguous, it could mean both: (1 + y) / a and: 1 + (y / a), put parentheses to enforce precedence in the wanted order.

You are not modifying the value of variable yes. It is always set to true.

Related

How can I set this so I can't enter any more than four numbers for cin?

I'm trying to make a simple user input. I tried to set it up so there would be four numbers entered by the user. It works for four inputs from user. It does not end after four separate numbers. Also managed to find out that I can trigger an endless repeating loop if one really long number is entered. Then I have to press cntrl+C to stop the code from running. This is in Microsoft Visual Studio if that is important.
#include <iostream>
using namespace std;
void GameBoy ()
{
cout<< "\nYou think you are this badass hacker so...." <<endl;
cout<< "Please enter the correct combination of numbers..." <<endl;
int a {};
int b {};
int c {};
int d {};
cin >> a >> b >> c >> d;
double sum = a + b + c + d;
int prod = a * b * c * d;
double average = sum / 4;
cout << average << endl;
if (sum != average && average == sum)
{
cout << "You're a goober!!" << endl;
}
else
{
cout << "You're still an goober :-P" << endl;
}
}
int main()
{
while (true)
{
GameBoy ();
}
return 0;
}
You can modify your function to return bool (true if all numbers are in the correct range, false if some number is out of range). Something like this:
#include <iostream>
using namespace std;
bool GameBoy() {
cout << "\nYou think you are this badass hacker so...." << endl;
cout << "Please enter the correct combination of numbers..." << endl;
int a{};
int b{};
int c{};
int d{};
cin >> a >> b >> c >> d;
double sum = a + b + c + d;
int prod = a * b * c * d;
double average = sum / 4;
cout << average << endl;
if (sum != average && average == sum) {
cout << "You're a goober!!" << endl;
} else {
cout << "You're still an goober :-P" << endl;
}
// if (Correct condition)
// return true;
// else Wrong condition
// return false
}
int main() {
while (GameBoy()) {
}
return 0;
}
I feel silly now. Just finished posting this question and found out what I needed to stop that endless loop. Once I added this then the issue stopped. Wow won't forget that!.
cin.clear();
cin.ignore();

I was writing some code and this error came up

There are 2 errors expression must be a modifiable lvalue (line 12) and expected a statement (line 25). I am new to c++ and i only know scratch and qbasic. I have been sitting in front of this error for almost 2 hours now.
Code:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int d;
cout << "Do you want Addition or Subtraction? (a/s)";
cin >> d;
if ('d' = "s");
{
int a, b;
cout << "Enter any number: ";
cin >> a;
cout << "Enter another number: ";
cin >> b;
int c = a + b;
cout << "The sum is ";
cout << c;
return 1;
}else{
int e, f;
cout << "Enter any number: ";
cin >> e;
cout << "Enter another number: ";
cin >> f;
int g = e + f;
cout << "The sum is ";
cout << g;
return 0;
}
}
Change
if ('d' = "s");
{
to
if (d == 's')
{
This fixes 4 problems in your code
the variable name is d & not 'd' (remove the single quotes around d in the if check. d is the variable int d. 'd' is the character d.
Conditional Check should be == & not =. = is assignment. == is conditional check. This is the cause for the l-value error (https://softwareengineering.stackexchange.com/questions/155665/what-are-the-key-terms-rvalue-and-lvalue)
The RHS of the conditional check should be 's' and not "s". Something between single quotes is a character. Something between double quotes is a string.
There should be no semicolon at the end of the if check. Remove it.
Also change int d to char d

C++ functions won't return values

#include<iostream>
#include<cstdlib>
#include<string>
#include<time.h>
using namespace std;
//Functions
// player strategy
int strategy(int user1Strat, int user2Strat);
// player total score per round
int currentScore();
// Display game result
void printResults();
int main()
{
int total_player1 = 0; // player 1 current score
int total_player2 = 0; // player 2 current score
int player1_strat= 0; //player 1 strategy for each turn
int player2_strat = 0; // player 2 strategy for each turn
// seed the random number generator.
srand(static_cast<int> (time(NULL)));
// get strategy for each player using functions <strategy>
strategy(player1_strat, player2_strat);
cout << player1_strat << endl << player2_strat << endl;
system("pause");
return 0;
}
int strategy(int user1Strat, int user2Strat)
{
int x,
y;
cout << "Enter player1's roll until strategy: ";
cin >> user1Strat;
cout << "Enter player2's roll until strategy: ";
cin >> user2Strat;
x = user1Strat;
y = user2Strat;
return x, y;
}
While calling for function strategy in the function main it will execute how it should, but once I ask to return the value it will just return
Enter player1's roll until strategy: 10
Enter player2's roll until strategy: 5
0
0
press any key to contiue...
Does anyone know why this is happening or what is causing it, was my error in the strategy function? Or upon calling it?
strategy(player1_strat, player2_strat); in your main() do nothing after receiving inputs so you won't see any change on player1_strat and player2_strat.
If you want to modify player1_strat and player2_strat in strategy, you could do that by referencing:
void strategy(int& user1Strat, int& user2Strat)
{
cout << "Enter player1's roll until strategy: ";
cin >> user1Strat;
cout << "Enter player2's roll until strategy: ";
cin >> user2Strat;
}
or you could return "multiple value" by using std::pair:
//#include <utility>
std::pair<int, int> strategy(int user1Strat, int user2Strat)
{
int x, y;
cout << "Enter player1's roll until strategy: ";
cin >> user1Strat;
cout << "Enter player2's roll until strategy: ";
cin >> user2Strat;
x = user1Strat;
y = user2Strat;
return std::make_pair(x, y);
}
//main()
std::pair<int, int> result = strategy(player1_strat, player2_strat);
x = result.first;
y = result.second;
You can only return a single object from a function. return x, y; does not return x and y but only y. If you want to update multiple variables, give them to the function as references and change their value inside the function.
Edit:
As mentioned by #Keith Thompson in the comments, the comma actually is an operator in this statement. It evaluates x (not much to do there), discards the result and then evaluates and returns the second argument y.

Adding a Probability Equation Into the Program

I've been working on this program in which it should calculate the probability based on the following formula:
𝑃(𝑥) = (𝑁!) / (𝑥!) * (𝑁−𝑥)!) * (p^x) * ((1-p)^(N-x))
Also, when the user types in a value, N must be an integer, x must be an integer which can be between 0 and N, and p must be a positive real number between 0 and 1. Till now this part works just fine but I don't know how to properly add the probability formula in the program.
The following is my code so far:
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
long int factorial (int N, int x, int p);
int main ()
{
double N, x, p;
cout << "Input N value" << endl;
cin >> N;
cout << "Input x Value" << endl;
cin >> x;
while(x<=0 || x>=N){
cout << "x value is NOT between 0 and N." << endl;
cout << "Input x Value" << endl;
cin >> x;
}
cout << "Input p value" << endl;
cin >> p;
while(p<=0 || p>=1){
cout << "p value is NOT a real number between 0 and 1." << endl;
cout << "Input p value" << endl;
cin >> p;
}
return 0;
}
Can anyone help me out just to understand how to properly add an equation in my program?
Thank you!
This is my new code:
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
double factorial (double N, double x, double p);
int main ()
{
double N;
double x;
double p;
cout << "Input N value" << endl;
cin >> N;
cout << "Input x Value" << endl;
cin >> x;
while(x<=0 || x>=N){
cout << "x value is NOT between 0 and N." << endl;
cout << "Input x Value" << endl;
cin >> x;
}
cout << "Input p value" << endl;
cin >> p;
while(p<=0 || p>=1){
cout << "p value is NOT a real number between 0 and 1." << endl;
cout << "Input p value" << endl;
cin >> p;
}
double Probability;
Probability = factorial(N, x, p);
cout << "Probability= " << Probability << endl;
return 0;
}
double factorial (double N, double x, double p){
double answer = ((tgamma(N+1))/((tgamma(x+1)) * (tgamma((N-x)+1)))) * (pow(p,x)) * (pow((1-p),(N-x)));
return answer;
}
The program recognizes the values I put in the system but when it calculates the answer, it gives a really small number. I tried out each section of the formula to make sure their was not a mistake but everything works fine when I tested it independently. Does anyone know what's wrong with the equation?
Thank you!
First you need to write a factorial function, check out this stackoverflow link:
How do you implement the factorial function in C++?
Then just write a function for your calculation. Assuming your factorial function is called getFact(int n) then:
double solve(int N, int x, double p) {
double answer = ( getFact(N)/getFact(x) )*getFact((N-x))* pow(p,x)* pow((1-p),(N-x));
return answer;
}
Then call the solve function in your main after having set your values.
double P_x;
P_x = solve(N,x,p);
Also, I use doubles because they can be more accurate, especially for p since its is 0 <= p <= 1.

C++ Structs Not Compiling... Not Initialized Properly? Not using them right?

I am -trying- to use nested structs/structures, and after several hours of pseudocode and attempts, the final result that I come up with doesn't work or doesn't compile.
I would like to take two vectors A and B, and compare them against each other. I set up nested struct to read the start and end point of the vector, and the vector struct itself. So I think I may be doing some wrong further below, but I am stuck.
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
struct Point // Reads in three coordinates for point to make a three dimensional vector
{
double x;
double y;
double z;
};
struct MathVector // Struct for the start and end point of each vector.
{
Point start;
Point end;
};
Point ReadPoint()
{
Point pt; // Letter distinguishes between vector A and vector B, or "letterA" and "letterB"
double x, y, z;
cout << "Please input the x-coordinate: " << endl;
cin >> pt.x;
cout << "Please input the y-coordinate: " << endl;
cin >> pt.y;
cout << "Please input the z-coordinate: " << endl;
cin >> pt.z;
return pt;
}
void DotProduct (MathVector letterA, MathVector letterB, double& a_times_b ) //formula to compute orthogonality
{
a_times_b = (letterA.end.x - letterA.start.x)*(letterB.end.x - letterB.start.x) + (letterA.end.y - letterA.start.y)*(letterB.end.y - letterB.start.y) + (letterA.end.z - letterA.start.z)*(letterB.end.z - letterB.start.z);
}
int main()
{
MathVector letterA;
MathVector letterB;
double a_times_b;
letterA = ReadPoint();
letterB = ReadPoint();
DotProduct (letterA, letterB, a_times_b);
cout << "The vector " << letterA << " compared with " << letterB << " ";
if ( a_times_b == 0)
cout << "is orthoganal." << endl;
else
cout << "is not orthoganal." << endl;
return 0;
}
One problem is with your ReadPoint whose return type is Point, but you're returning an instance of MathVector. Also, you read the input into variables which ignore eventually.
You should write ReadPoint as:
Point ReadPoint()
{
Point p;
cout << "Please input the x-coordinate: " << endl;
cin >> p.x;
cout << "Please input the y-coordinate: " << endl;
cin >> p.y;
cout << "Please input the z-coordinate: " << endl;
cin >> p.z;
return p;
}
Or a little better version:
Point ReadPoint()
{
Point p;
cout << "Please enter point-coordinate : " << endl;
cin >> p.x >> p.y >> p.z; //example input : 1 2 3
return p;
}
Or, still better is, overload >> operator as:
std::istream & operator>>(std::istream & in, Point & p)
{
cout << "Please enter point-coordinate : " << endl;
return cin >> p.x >> p.y >> p.z; //example input : 1 2 3
}
//Use this as
Point pointA, pointB;
cin >> pointA >> pointB;
Now read a good C++ book. If you're already reading one, then make sure it is really good. Here is a list of really good C++ books, of all levels:
The Definitive C++ Book Guide and List
ReadPoint returns letter of type MathVector instead of Point
You haven't overloaded operator << to tell it how to handle MathVector objects
letterA and letterB are of type MathVector
MathVector letterA;
MathVector letterB;
double a_times_b;
letterA = ReadPoint();
letterB = ReadPoint();
you should create another method to read Mathvector.. as you are doing with Point.
and in method ReadPoint
return type must be Point .. If you reading point then do calculation here to create the object of MathVector go tet startpoint and endpoint format.
Point ReadPoint()
{
MathVector letter; // Letter distinguishes between vector A and vector B, or "letterA" and "letterB"
double x, y, z;
cout << "Please input the x-coordinate: " << endl;
cin >> x;
cout << "Please input the y-coordinate: " << endl;
cin >> y;
cout << "Please input the z-coordinate: " << endl;
cin >> z;
return letter;
}
You didn't explain what it is you're trying to do or what errors you got, but this code makes no sense. You have three variables, x, y, and z. You fill them with values you get from the user. Then you don't do anything with those variables and return the MathVector created by a default constructor even though you say you're going to return a Point. That makes very little sense.
No match for 'operator=' error means that there's no function for assigning a MathVector to a Point. You are calling ReadPoint() which returns a Point and trying to assign the returned value to a variable of type MathVector. The compiler can't create a 'convertion' function automatically. You have to provide one yourself. Perhaps what you meant was
letterA.start = ReadPoint();
letterA.end = ReadPoint();