Why do my if statements not work in for loops? - c++

So this is my second program I've tried writing an if statement in a for loop. The first one was unnecessary, but this one "needs" it. I put needs in quotes because I'm new to C++ and have not learned/thought of another method.
My program:
int main()
{
int x, z;
cout << " x | z | y\n"
<< "---------------------------\n";
for (x = 1; x <=5; x++)
{
for (z = 2; z <= 6; z++)
{
double y = x*z/(x-z);
if (x - z == 0)
{
cout << setw(2) << x << setw(4) << z << setw(21) << "Function Undefined\n";
}
else if (x - z != 0)
{
cout << setw(2) << x << setw(4) << z << setw(21) << y << endl;
}
}
}
return 0;
}
When I run this, I get a table with the first loop sequence (x = 1) completed, but then it crashes (Windows is looking for solution box pops up). It writes out the correct values only for x = 1 (the outer loop does not repeat to x = 2 and so on).
Why is this happening?

«whisper»...hey...you are dividing by 0 boy...

You put the if statement just before the actual math. If you divide by zero, an error will occur.
Put the math in the else if block.

Related

My function factoring program has problems with variables, shows incorrect answers

I'm making a program that factors functions (f(x), not fully factored though):
#include <iostream>
#include <math.h>
#include <stdio.h>
using namespace std;
int x3;
int x2;
int x;
int remain;
int r = 0;
int factor;
int main() {
int b, i, j = 0;
int factors[101];
cout << "f(x) = x^3 + x^2 + x + r (Factor tool)" << endl;
cout << "x^3?: ";
cin >> x3;
cout << "x^2: ";
cin >> x2;
cout << "x: ";
cin >> x;
printf("remain (Y intercept): ");
scanf("%d", &b);
cout << "f(x) = " << x3 << "x^3 + " << x2 << "x^2 + " << x << "x + " << b
<< "" << endl;
cout << "factors of remainder are: " << endl;
for (i = 1; i <= b; i++) {
if (b % i == 0) {
factors[j++] = i;
printf("%d\t", i);
}
}
getchar();
while (true) {
int good;
if (factors[1] == 0) {
cout <<endl;
cout << "Equation Cannot be factored";
break;
}
int factorv = factors[r];
int nx1 = x3 * factors[r];
int nx2 = (nx1 + x2);
int nx3 = x + (nx2 * factors[r]);
int nx4 = remain + (nx3 * factors[r]);
if (nx4 == 0) {
int factored = (0 - factors[r]);
cout <<endl;
cout << "The Factored Function: f(x) = "
<< "(x " << factored << ")(" << nx1 << "x^3 + " << nx2 << "x^2 + "
<< nx3 << "x"
<< ")"
<< "";
break;
} else {
r = r + 1;
}
}
}
but in this part of the code, it shows as (x 0)(0x^3 + (x3 input instead of calculated nx1)x^2 + (x2 input instead of calculated nx2)x).
if (nx4 == 0) {
int factored = (0-factors[r]);
cout<<"The Factored Function: f(x) = "<<"(x "<<factored<<")("<<nx1<<"x^3 + "<<nx2<<"x^2 + "<<nx3<<"x"<<")"<<"";
break;
What happen to my nx variables? Why is it coming up incorrect or as a 0 when it was calculated properly above?
You have some of your variables twice:
int nx1;
int nx2;
int nx3;
int nx4;
They exists as global variables and again in the scope of main. They have the same name but are different variables.
Take the lesson: Global variables are no good.
Moreover you have a logic error in your code. When I add a std::cout << r << std::endl; in the last while loop I see its value increasing until there is a segfault, because factors[r] is out-of-bounds. broken code # wandbox
I cannot really tell you how to fix it, because I would have to dive into the maths first. I can only suggest you to never use infinte loops in numerical codes without an "emergency exit". What i mean is that unless fully tested, you cannot be sure that the loop will end at some point and when it doesn't typically the consequences are bad and difficult to diagnose. Always make sure the loop will end at some point:
int max_iteratons = 100;
int counter;
while (counter < max_iteratons) {
// do something
++counter;
}
if (counter == max_iterations) std::cout << "i have a bug :(";

How to make the output in tabular form

Who could help me, can't figure out how to make my output for Charge-column. I need to make that output right under that charge column, but every time when I hit ENTER it makes a new line hence my output appears in new line. Also there is a zero after each output, don't know where is that come from. Here is my code:
#include<iostream>
#include<stdlib.h>
#include<time.h>
using namespace std;
float calculateCharges(double x);
int main()
{
int ranQty; //calculates randomly the quantity of the cars
double pTime; // parking time
srand(time(NULL));
ranQty = 1 + rand() % 5;
cout << "Car\tHours\tCharge" << endl;
for(int i = 1; i <= ranQty; i++)
{
cout << i << "\t";
cin >> pTime ;
cout << "\t" << calculateCharges(pTime) << endl;
}
return 0;
}
float calculateCharges(double x)
{
if(x <= 3.0) //less or equals 3h. charge for 2$
{
cout << 2 << "$";
}
else if(x > 3.0) // bill 50c. for each overtime hour
{
cout << 2 + ((x - 3) * .5) << "$";
}
}
You are hitting ENTER key each time to send your pTime from the command line to your program's standard input. This causes a new line. The new line is what causes the console to hand your input over to the program in the first place.
In order to print properly, you can simply store the pTime to an array(i.e, preferably in std::vector, as #user4581301 mentioned); calculate the required and print it.
something like:
#include <vector>
ranQty = 1 + rand() % 5;
std::cout << "Enter " << ranQty << " parking time(s)\n";
std::vector<double> vec(ranQty);
for(double& element: vec) std::cin >> element;
std::cout << "Car\tHours\tCharge" << std::endl;
for(int index = 0; index < ranQty; ++index)
std::cout << index + 1 << "\t" << vec[index] << "\t" << calculateCharges(vec[index]) << "$" << std::endl;
there is a zero after each output, don't know where is that come from.
float calculateCharges(double x); this function should return a float and your definition is something like a void function. Solution is:
float calculateCharges(double x)
{
if(x <= 3.0) return 2.0f; // --------------> return float
return 2.0f + ((x - 3.0f) * .5f) ; // --------------> return float
}

Simple for loop I can't figure out

I'm kind of new to C++ so last night I thought of something. I want to print out numbers from 1-100 but with 10 numbers per line. I'm aware my code is below is wrong as it just prints 1-100 vertically. If anyone can shed some light to my question, it would be greatly appreciated. Thanks for reading :)
#include <iostream>
using namespace std;
int main() {
for(int x = 1; x <= 100; x++) {
cout << x << endl;
}
}
So you want to print 10 numbers, then a carriage return, and then 10 numbers, then a carriage return, and so on, correct?
If so, how about something like:
for(int x = 1; x <= 100; x++) {
cout << x << " ";
if ((x%10)==0) cout << endl;
}
Use the modulo operator % to determine if a number is a multiple of another:
for(int x = 1; x <= 100; x++) {
if( x % 10 == 0 ) cout << endl;
cout << x << " ";
}
How about
int main() {
for(int x = 1; x <= 100; x++) {
cout << x << " " ; //Add a space
if ( x % 10 == 0 ) {
cout << endl //Put out a new line after every 10th entry?
}
}
}
Print new line when it can be device by 10.
for(int x = 1; x <= 100; x++) {
cout << x << ",";
if ((x % 10) == 0) {
cout << endl;
}
}
for(int i=1; i<=100; i++) {
i%10==0 ? cout << i<<endl : cout<<i<<" ";
}

How to display "No solution" instead of -1.#IND in do while loop?

I'm trying to calculate y with x going from -1 to 1. If y cannot be calculated with current x value, it should display "No solution". My code:
void main()
{
double y, t, x = -1;
do {
t = sqrt(sin(pow(x, 2))) / (x - 2);
y = sqrt(2 * t + x);
cout << "x = " << x << endl;
cout << "t = " << t << endl;
cout << "y = " << y << endl;
cout << endl;
x++;
} while (x <= 1);
_getch();
And this is the output I get:
x = -1
t = -0.305772
y= -1.#IND
x = 0
t = -0
y= 0
x = 1
t = -0.917317
y= -1.#IND
So if result is y= -1.#IND It should display "y = No solution"
Two options:
check for a non-negative value before calling sqrt
check whether the result is a number with std::isnan.
I'd favour the first, since it avoids unnecessary calculations, and works with any floating-point implementation. The second might cause a run-time error, rather than return a "not-a-number" result, on some implementations.

Error in displaying the largest and smallest number

I was attempting to write a program for exercise 2.19 in How to Program, but I ran into some difficulties.
The program is supposed to have the user enter three integers and then display the sum, average, and product of those integers.
The only problem I am having is with displaying the largest and smallest. When I ran the program and entered three integers (8, 9, and 10), the output read Smallest is 8 AND Smallest is 9.
I was hoping you could tell me why.
#include <iostream>
using namespace std;
int main ()
{ int x, y, z, sum, ave, prod;
cout << "Input three different integers ";
cin >> x >> y >> z;
sum = x + y + z;
cout << "\nThe sum is " << sum;
ave = (x + y + z) / 3;
cout << "\nThe average is " << ave;
prod = x * y * z;
cout << "\nThe product is " << prod;
if (x < y, x < z)
{cout << "\nSmallest is " << x;}
if (y < x, y < z)
{cout << "\nSmallest is " << y;}
if (z < x, z < y)
{cout << "\nSmallest is " << z;}
if (x > y, x > z)
{cout << "\nLargest is " << x << endl;}
if (y > x, y > z)
{cout << "\nLargest is " << y << endl;}
if (z > x, z > y)
{cout << "\nLargest is " << z << endl;}
return 0;
}
P.S. I am doing this to study, this is not homework.
You need to rewrite this if condition
if (x < y, x < z)
to be
if (x < y && x < z)
and do the same for all of the remaining if conditions you have.
Edit:
All experssions seperated by comma will be evaluated so if you have something like that
x = 5, y = 6; it will evaluate both of them and set x to 5 and y to 6
but
z = (x=5, y=6); this will cause z to be set to 6 just like y as y=6 was the last term in the list of comma separated terms.
int main() {
std::cout << "Enter three numbers: ";
int sum = 0;
double avg = 0.;
int product = 0;
int smallest = std::numeric_limits<int>::max();
int largest = std::numeric_limits<int>::min(); // the initializers here might not be correct, but the gist is in place...
for (int i = 0; i < 3; ++i) {
int val = 0;
std::cin >> val;
sum += val;
avg += val;
product *= val;
if (val < smallest) smallest = val;
if (val > largest) largest = val;
}
avg /= 3.; // This can also be done in the for loop, I just forget how.
std::cout << "Sum: " << sum;
// etc... The calculations are all done.
}
Replace your commas, with && for an AND operator, meaning both of the conditions have to be true, or || which is an OR operator, if you want any or both conditions to be satisfied.
from C++ docs:
The comma operator (,) is used to separate two or more expressions that are included
where only one expression is expected. When the set of expressions has to be evaluated
for a value, only the rightmost expression is considered.
Instead of comma, you want &&
i.e.
if (x < y , x < z)
{cout << "\nSmallest is " << x;}
should be
if (x < y && x < z)
{cout << "\nSmallest is " << x;}
Use && in place of , inside your if conditions.
By now you realize that && is for AND and that you should use this operator instead of the comma, ,. But did you know you can also use they keyword and in place of its symbol equivalent?:
if ( x < y and x < z ) {
}