For my class I'm programming a square root function using inclusion. No, I may not use any other method...
This is my code so far, with the program nearly working. It works for perfect square roots and some other values (like 11 or 5) but it gets into an infinite loop for others (8, 2).
The reason why this happens is that the upper and lower bounds (b and a) do not change. Ideally, the bounds would be current x and previous x, creating new x. What happens is that new x is currently formed by current x and either a or b, being a constant.
I've tried for so long but I have not yet found a way to 'remember' or find the 'previous x', as every time the while loop repeats, only the current x is available for use. Anyone know how such a problem could be solved?
void inclusion ()
{
double v ;
cout << "*** Now solving using Inclusion ***" << endl << "To calculate the square root, enter a positive number: " ;
cin >> v ;
while (v<0)
{
cout << "Square roots of negative numbers cannot be calculated, please enter a positive number: " ;
cin >> v ;
}
cout << endl ;
int n = 0;
while (v >= n*n)
n++ ;
double b = n ;
double a = n-1 ;
int t = 0 ;
double x = (a+b)/2 ;
while ((x * x - v >= 0.1) || (x * x - v <= -0.1))
{
t++ ;
if (x * x < v)
{
cout << "Lower Bound: " << x << '\t' << '\t' ;
cout << "Upper Bound: " << b << '\t' << '\t' ;
x = (b + x)/2 ;
cout << "Approximation " << t << ": " << x << endl ;
}
else
{
cout << "Lower Bound: " << a << '\t' << '\t' ;
cout << "Upper Bound: " << x << '\t' << '\t' ;
x = (a + x)/2 ;
cout << "Approximation " << t << ": " << x << endl ;
}
}
cout << endl << "The answer is " << x << ". Iterated " << t << " times." << endl << endl ;
}
I have not yet found a way to 'remember' or find the 'previous x'
Have a variable previous_x that you previous_x = x at the end of the loop
But that's not your problem. You are changing x, but not a or b, so you get into an infinitely repeating pattern. You should instead adjust whichever bound brings you tighter in.
void inclusion ()
{
double v ;
cout << "*** Now solving using Inclusion ***" << endl << "To calculate the square root, enter a positive number: " ;
cin >> v ;
while (v<0)
{
cout << "Square roots of negative numbers cannot be calculated, please enter a positive number: " ;
cin >> v ;
}
cout << endl ;
int n = 0;
while (v >= n*n)
n++ ;
double b = n ;
double a = n-1 ;
int t = 0 ;
double x;
for (x = (a+b)/2; abs(x * x - v) >= 0.1; x = (a+b)/2, ++t)
{
if (x * x < v)
{
cout << "Lower Bound: " << x << '\t' << '\t' ;
cout << "Upper Bound: " << b << '\t' << '\t' ;
a = (b + x)/2 ;
cout << "Approximation " << t << ": " << x << endl ;
}
else
{
cout << "Lower Bound: " << a << '\t' << '\t' ;
cout << "Upper Bound: " << x << '\t' << '\t' ;
b = (a + x)/2 ;
cout << "Approximation " << t << ": " << x << endl ;
}
}
cout << endl << "The answer is " << x << ". Iterated " << t << " times." << endl << endl ;
}
You need to update the bounds too:
a = x;
x = (b + x)/2;
and
b = x;
x = (a + x)/2;
Related
I'm a fairly new to c++. I'm trying to create a very basic calculator and the results I'm getting are completely wrong. I've come to a standstill after 2 hours of trying everything in my knowledge. What am I doing wrong?
#include <iostream>
using namespace std;
int main()
{
int a = 0.0;
int b = 0.0;
float sum = 'a' + 'b';
float diff = 'a' - 'b';
float prod = 'a' * 'b';
float quot = 'a' / 'b';
float rem = 'a' % 'b';
//Input
cout << "Enter a number: " << endl;
cin >> a;
cout << "Enter another number: " << endl;
cin >> b;
cout << a << " + " << b << " = " << sum <<endl;
cout << a << " - " << b << " = " << diff <<endl;
cout << a << " / " << b << " = " << quot <<endl;
cout << a << " * " << b << " = " << prod <<endl;
cout << a << " % " << b << " = " << rem <<endl;
return 0;
}
you are calculating with character literals. 'a' is not the same as a here.
remove the quotes when calculating, but add them when you print the actual literal "a"
float sum = 'a' + 'b';
You are calculating the ASCII value of the character "a" (which is 65) with the ASCII value of "b" (which is 66)
It should be
float sum = a + b;
instead.
When you print the values, you did the reverse:
cout << a << " + " << b << " = " << sum <<endl;
You want it to be
cout << "a" << " + " << "b" << " = " << sum <<endl;
instead. You want to print characters for the equation and only a number for the result.
You also calculate the values of a and b before they have an actual value.
You should put the calculation after you enter them.
Fixed, by moving the calculations after the input; and by using variables, not literals.
#include <iostream>
using namespace std;
int main()
{
int a = 0.0;
int b = 0.0;
//Input
cout << "Enter a number: " << endl;
cin >> a;
cout << "Enter another number: " << endl;
cin >> b;
float sum = a + b;
float diff = a - b;
float prod = a * b;
float quot = a / b;
float rem = a % b;
cout << a << " + " << b << " = " << sum <<endl;
cout << a << " - " << b << " = " << diff <<endl;
cout << a << " / " << b << " = " << quot <<endl;
cout << a << " * " << b << " = " << prod <<endl;
cout << a << " % " << b << " = " << rem <<endl;
return 0;
}
I'm trying to make a football tournament in C++, in which the user inputs the name of the teams(8 teams) and then each team has to play with the other one 1 time. Firstly, I don't know how to read the team names, I mean I tried to use .getline or just cin of a char array, but then I need to put the teams into the matrix and after the final game my program should print the table. So there's the first question: how to read the names and basically make the program think they are numbers or does it work with just with names, no need to use int? And then the users inputs the result for every game, but here comes the hard part. After all the results have been introduced, the matrix rotates cyclic and then the result stored in the variables(you will see in code victory/losses) overwrites themselves, so at the end, I cannot print the right table. So that's the second question: How can I make them store to the right 'team' while they rotate? Sorry if I didn't quite explain very well how it works, hope you understand it. Cheers!
// FOOTBALL TOURNAMENT
int map[2][4];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 4; j++) {
cout << "map[" << i << "][" << j << "]= ";
cin >> map[i][j];
}
}
cout << "The map looks like this:" << endl;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 4; j++) {
cout << map[i][j] << " ";
}
cout << endl;
}
map[0][0] = 1;
int temp = 0, temp2 = 0, temp3 = 0, temp4 = 0, temp5 = 0, temp6 = 0;
int a, b, c, d, e, f, g, h, round = 0;
int victory_m00(0), losses_m10(0), victory_m10(0), losses_m00(0), victory_m01(0), losses_m11(0), victory_m11(0), losses_m01(0);
int victory_m02(0), losses_m12(0), victory_m12(0), losses_m02(0), victory_m03(0), losses_m13(0), victory_m13(0), losses_m03(0);
do
{
// Insert result for every game
cout << "Enter the result of the first game between " << map[0][0] << " vs. " << map[1][0] << endl;
cin >> a >> b;
if (a > b) {
victory_m00++;
losses_m10++;
}
else if (a < b)
{
victory_m10++;
losses_m00++;
}
cout << "Enter the result of the first game between: " << map[0][1] << " vs. " << map[1][1] << endl;
cin >> c >> d;
if (c > d) {
victory_m01++;
losses_m11++;
}
else if (c < d)
{
victory_m11++;
losses_m01++;
}
cout << "Enter the result of the first game between: " << map[0][2] << " vs. " << map[1][2] << endl;
cin >> e >> f;
if (e > f) {
victory_m02++;
losses_m12++;
}
else if (e < f)
{
victory_m12++;
losses_m02++;
}
cout << "Enter the result of the first game between: " << map[0][3] << " vs. " << map[1][3] << endl;
cin >> g >> h;
if (g > h) {
victory_m03++;
losses_m13++;
}
else if (g < h)
{
victory_m13++;
losses_m03++;
}
round++;
// Map switching
temp = map[1][0];
map[1][0] = map[0][1];
temp2 = map[1][1];
map[1][1] = temp;
temp3 = map[1][2];
map[1][2] = temp2;
temp4 = map[1][3];
map[1][3] = temp3;
temp5 = map[0][3];
map[0][3] = temp4;
temp6 = map[0][2];
map[0][2] = temp5;
map[0][1] = temp6;
// Table calculating and printing ~ also this has to be outside the loop (but at first i wanted to print the table after every 'round'
cout << "This is how the table looks like after the " << round << " round: \n";
cout << map[0][0] << " has: " << victory_m00 << " victory(-ies) and " << losses_m00 << " loss-es!\n";
cout << map[0][1] << " has: " << victory_m01 << " victory(-ies) and " << losses_m01 << " loss-es!\n";
cout << map[0][2] << " has: " << victory_m02 << " victory(-ies) and " << losses_m02 << " loss-es!\n";
cout << map[0][3] << " has: " << victory_m03 << " victory(-ies) and " << losses_m03 << " loss-es!\n";
cout << map[1][0] << " has: " << victory_m10 << " victory(-ies) and " << losses_m10 << " loss-es!\n";
cout << map[1][1] << " has: " << victory_m11 << " victory(-ies) and " << losses_m11 << " loss-es!\n";
cout << map[1][2] << " has: " << victory_m12 << " victory(-ies) and " << losses_m12 << " loss-es!\n";
cout << map[1][3] << " has: " << victory_m13 << " victory(-ies) and " << losses_m13 << " loss-es!\n";
cout << endl;
cout << endl;
} while (map[0][1] != 2);
```
I get the following output:
This program is designed to aid in the analysis of triangles.
Would you like to specify the coordinates of a triangle (C),
or the lengths of their sides(S) ? Enter 'C' or 'S: s
Enter the length of side a: 3
Enter the length of side b: 4
Enter the length of side c: 5
The coordinates are A(0,0) , B(5,0) , C(nan,nan)
The angles are A = nan, B = nan and C = nan
The desired output is:
The coordinates of the triangle are at A(0,0), B(5,0) and C(3.2,2.4). The angles are A = 0.643501, B = 0.927295, and C = 1.5708
I've tried declaring variables in the beginning of main, as well as initializing them to 0. I either get a nan error or the incorrect values for my output
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
const double PI = 3.1415926535897932384626433832795;
int main() {
char mode = ' ';
cout << "\n\n";
cout << setw(10) << "" << "This program is designed to aid in the analysis of triangles. " << endl;
cout << setw(10) << "" << "Would you like to specify the coordinates of a triangle (C), " << endl;
cout << setw(10) << "" << "or the lengths of their sides(S) ? Enter 'C' or 'S: " ;
while (cin >> mode)
{
if (mode == 'C' || mode == 'c')
{
double Ax, Ay, Bx, By, Cx, Cy;
cout << "\n";
cout << setw(10) << "" << "Enter the x coordinate of point A: ";
cin >> Ax;
cout << setw(10) << "" << "Enter the y coordinate of point A: ";
cin >> Ay;
cout << setw(10) << "" << "Enter the x coordinate of point B: ";
cin >> Bx;
cout << setw(10) << "" << "Enter the y coordinate of point B: ";
cin >> By;
cout << setw(10) << "" << "Enter the x coordinate of point C: ";
cin >> Cx;
cout << setw(10) << "" << "Enter the y coordinate of point C: ";
cin >> Cy;
double a = sqrt((Cx - Bx) * (Cx - Bx) + (Cy - By) * (Cy - By));
double b = sqrt((Ax - Cx) * (Ax - Cx) + (Ay - Cy) * (Ay - Cy));
double c = sqrt((Ax - Bx) * (Ax - Bx) + (Ay - By) * (Ay - By));
double A = acos(((b * b) + (c * c) - (a * a)) / 2 * b * c);
double B = asin(b*sin(A) / a);
double C = asin(c*sin(A) / a);
cout << "\n" << setw(10) << "" << "The lengths of the sides are: a = " << a << ", b = " << b << " and c = " << c << endl;
cout << setw(10) << "" << "The angles are A = " << A << ", B = " << B << " and C = " << C << endl;
}
else if (mode == 'S' || mode == 's')
{
double a = 0, b = 0, c = 0;
cout << setw(10) << "" << "Enter the length of side a: ";
cin >> a;
cout << setw(10) << "" << "Enter the length of side b: ";
cin >> b;
cout << setw(10) << "" << "Enter the length of side c: ";
cin >> c;
if (a + b > c && b + c > a && a + c > b)
{
double A = acos(((b * b) + (c * c) - (a * a)) / 2 * b * c);
double B = asin(b*sin(A) / a);
double C = asin(c*sin(A) / a);
double Ax = 0;
double Ay = 0;
double Bx = c;
double By = 0;
double Cx = b * (cos(A) * PI / 180);
double Cy = b * (sin(A) * PI / 180);
cout << setw(10) << "" << "The coordinates are A(" << Ax << "," << Ay << ") , B(" << Bx << "," << By << ") , C(" << Cx << "," << Cy << ")" << endl;
cout << setw(10) << "" << "The angles are A = " << A << ", B = " << B << " and C = " << C << endl;
}
else
cout << setw(10) << "" << "These lengths don't form a triangle. Try again";
}
else
{
cout << setw(10) << "" << "Please enter 'S' or'C': ";
cin >> mode;
}
}
}
multiplication(*) and division(/) operators are having same precedence and associativity is left-to-right, just change the angle A calculation to
double A = acos(((b * b) + (c * c) - (a * a)) / (2 * b * c));
I can't seem to find what's wrong with my code, I'm trying to end the loop once the answers is equals to 0 but it keeps going on an infinite loop.
#include <iostream>
int main() {
using namespace std;
int x, remainder;
cout << "please enter a positive integer number: " << endl;
string tab;
tab = '\t';
cin >> x;
remainder = x % 2;
do{
while ( x % 2 != 0)
{
cout << x << " is odd" << tab << "Subtract 1" << tab << " Half of " << x - 1 << " is " << x / 2;
x = (x - 1) / 2;
cout << endl;
}
while (x % 2 == 0)
{
cout << x << " is even" << tab << "Subtract 0" << tab << "Half of " << x << " is " << x / 2;
x = x / 2;
cout << endl;
}
}
while (x >= 0);
}
There are, essentially, two problems in your code, both of which, in themselves, will make your loop run endlessly.
Starting from the outside and working inwards: The test at the end of your (outer) while loop will always be "true", as you have while (x >= 0); so, even when x gets to zero (as it will), the loop will keep running! (And, once x is zero it will remain zero!)
Second, the two 'inner' while loops shouldn't be loops at all! You want one or the other 'block' to run once only for each main loop - so use an if ... else structure.
The following is a corrected version of your code:
#include <iostream>
int main() {
// using namespace std; // Generally, not good practice (and frowned-upon here on SO)
using std::cin; using std::cout; using std::endl; // Use only those you want to!
using std::string;
int x, remainder;
cout << "please enter a positive integer number: " << endl;
string tab;
tab = '\t';
cin >> x;
remainder = x % 2;
do {
if (x % 2 != 0)
{
cout << x << " is odd" << tab << "Subtract 1" << tab << " Half of " << x - 1 << " is " << x / 2;
x = (x - 1) / 2;
cout << endl;
}
else // if (x % 2 == 0) ... but we don't need to test this again.
{
cout << x << " is even" << tab << "Subtract 0" << tab << "Half of " << x << " is " << x / 2;
x = x / 2;
cout << endl;
}
} while (x > 0); // You run forever if you have x >= 0!
return 0;
}
There are a few other things that could be changed to make the code more "efficient," but I'll let you peruse the MNC (Minimum Necessary Change) before we start editing towards a BPC (Best Possible Code)!
EDIT: OK, due to 'peer pressure' from comments 😊, I'll put in a suggested BPC now:
#include <iostream>
int main() {
using std::cin; using std::cout; using std::endl; // Use only those you want to!
int x;// , remainder; // "remainder" is never used, so we can discard it!
cout << "Please enter a positive integer number: " << endl;
cin >> x; // Not critical, but I like to put such a cin right after the prompting cout.
std::string tab{ "\t" }; // Let's initialise more directly!
do {
// As there is only one line (now) inside each if/else block, we can leave out the {} ...
if (x % 2 != 0)
cout << x << " is odd" << tab << "Subtract 1" << tab << "Half of " << x - 1 << " is " << x / 2;
else
cout << x << " is even" << tab << "Subtract 0" << tab << "Half of " << x << " is " << x / 2;
// We can put the following two line outside the tests, as they will be the same in both cases:
x = x / 2; // When x is ODD, this will give the SAME answer as x = (x - 1)/2 (as you noticed in your first cout)
cout << endl;
} while (x > 0); // You run forever if you have x >= 0!
return 0;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
i want to know how to turn this if else statement to a switch statement.this is a c++ program to out put the integers in the right order. i can't figure out a way.please help.thank you in advance.
int x, y, z;
cout << "please enter three integers:";
cin >> x >> y >> z;
if (x <= y && y <= z)
cout << x << " " << y << " " << z << endl;
else if (x <= z && z <= y)
cout << x << " " << z << " " << y << endl;
else if (y <= z && z <= x)
cout << y << " " << z << " " << x << endl;
else if (y <= x && x <= z)
cout << y << " " << x << " " << z << endl;
else if (z <= x && x <= y)
cout << z << " " << x << " " << y << endl;
else
cout << z << " " << y << " " << x << endl;
if (x <= y) {
if (z <= x) {
cout << z << " " << x << " " << y << endl;
} else {
if (z <= y) {
cout << x << " " << z << " " << y << endl;
} else {
cout << x << " " << y << " " << z << endl;
}
}
} else {
if (z >= x) {
cout << y << " " << x << " " << z << endl;
} else {
if (y >= z) {
cout << z << " " << y << " " << x << endl;
} else {
cout << y << " " << z << " " << x << endl;
}
}
}
That is not a good way to write a program. What if you need 4 integers?
One way to do it would be to use a list like std::vector and sort it.
vector<int> numbers;
int number = 0;
while (numbers.size() < 3 && cin >> number)
numbers.push_back(number);
sort(cbegin(numbers), cend(numbers)); // sorts ascending by default
for (auto number : numbers)
cout << number << " ";
cout << endl;
You can also use std::multiset which sorts its items automatically as they are inserted.
Instead of this approach, why don't you store the input in an array and try any of the sorting alogrithms to sort your input?
The answer in your particular case is you can't,
Your if statements have particular conditions, which,
wouldn't really work inside a switch.
An example of if/else if/else statements that can be
translated into a switch would be:
if(i == 1) {
// code here
} else if(i == 2) {
// code here
} else if(i == 3) {
// code here
} else {
// code here
}
which would translate to:
switch(i) {
case 1:
//code here
break;
case 2:
//code here
break;
case 3:
//code here
break;
default:
//code here
break;
}
Hope that helps a bit to understand a little more about switch statements.
If the challenge is that you can't sort the numbers, and the limit is 3 integers, then there are better ways to accomplish what you're doing.
#include <iostream>
using namespace std;
int main()
{
int combo[6][3] = {{0,1,2},{0,2,1},{1,0,2},{1,2,0},{2,0,1},{2,1,0}};
int values[3];
cin >> values[0] >> values[1] >> values[2];
for (int i = 0; i < 6; ++i )
{
if ( values[combo[i][0]] <= values[combo[i][1]] &&
values[combo[i][1]] <= values[combo[i][2]] )
{
cout << values[combo[i][0]] << " " << values[combo[i][1]] <<
" " << values[combo[i][2]];
break;
}
}
}
The combo array holds all of the combinations that can occur with 3 slots. Also note that the input is an array. Even if you didn't use the loop, the maximum if() statements you would need is 6.
However you should mention up front that this is a challenge, and what the restrictions are. Otherwise, please look at the other answers concerning storing and sorting these numbers.
You only need three conditional swaps to sort a list of three elements:
int x, y, z;
cout << "please enter three integers:";
cin >> x >> y >> z;
if (y < x) swap(y, x);
if (z < y) swap(z, y);
if (y < x) swap(y, x);
cout << x << " " << y << " " << z << endl;
Note that this approach doesn't scale. For 10 numbers, you would already need 45 conditional swaps.