Nested loops to find max - c++

I am coding a program to find the maximum of an equation over an interval given by the user. When I compile the code instead of outputting the maximum it gives me this
Please enter the first number of the interval to be checked:
Please enter the last number of the interval to be checked:
Please enter the desired initial step size:
sh: PAUSE: command not found
I figure the problem has to do with my loops, but I'm not sure how to rectify the situation.
Here's my code
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int a, b, delta, x, y;
int max = 0;
cout <<"Please enter the first number of the interval to be checked: " << endl;
cin >> a;
cout << "Please enter the last number of the interval to be checked: " << endl;
cin >> b;
cout << "Please enter the desired initial step size: " << endl;
cin >> delta;
for(x = a; x <= b; x = x+delta)
{
y = pow(x, 2)-7*x-18;
if (y > max)
{
max = y;
cout <<"The maximum over the interval from " << a <<" to " << b <<" is " << max;
}
else
{
delta= delta/2;
}
if (delta < pow( 10, -6))
{
break;
}
}
return 0;
}

Looking at your code it seems like that the value of delta should be in float as you are recursively dividing it by 2. Your pow (10,-2) doesn't do any useful comparison for that matter. even after everything it doesn't throw me that pause error. I ran it on VS 12 (C++11).

Related

Ask for the condition of guess number game

I am a newbie, i have some question:
I am coding a guessing number game, player enter the random number range, guess number, guess limit. When player enter the guess number out of the random range entered, the program require player to enter the guess number again. However, I tested my code, I entered the number range [ 3,8 ] and the guess number is 1, this number is out of range, the program didn't force me to enter the guess number again but I had to enter the guess limit. Please hint me what's wrong with my code and help me to fix this code. Thanks!
#include iostream
#include cstdlib
using namespace std;
int randnum(int min, int max)
{
return min + (int)(rand() * (max - min + 1.0) / (1.0 + RAND_MAX));
}
int main()
{
int max;
int min;
int guessnum;
int guesscou = 0;
int guesslim;
bool outofguess = false;
cout << " Enter max min of random value range = \n ";
cin >> max >> min;
cout << " Enter your guess number = \n ";
cin >> guessnum;
cout << " Enter your guess limitation = \n";
cin >> guesslim;
// enter guess loop
while (guessnum != randnum(min, max) && !outofguess) {
// guessnum condition
while (guessnum <= max && guessnum >= min) {
cout << " Unvalid number, please enter again ";
cin >> guessnum;
}
// guess limitation
if (guesscou <= guesslim) {
cout << " Please try again \n";
cin >> guessnum;
guesscou++;
}
else {
outofguess = true;
}
}
if (outofguess) {
cout << " you win";
}
else {
cout << " you lose ";
}
}
You want the user to guess again if the number is lower than the minimum or higher than the maximum. But the logic in your while loop says exactly the opposite. It should read
while (guessnum < min || guessnum > max) {
cout << " Unvalid number, please enter again ";
cin >> guessnum;
}

C++ - Check if there are no even numbers in given interval

I have to write a program on C++ which finds all even numbers in range given by user. Here's the code I have written so far:
#pragma hdrstop
#pragma argsused
#include <tchar.h>
#include <iostream.h>
#include <conio.h>
#include <stdio.h>
#include <math.h>
void main() {
int m, n, j = 1; // m and n- numbers entered by user, j- product of all even numbers in interval
char atbilde; // A letter entered by user, of which system decides wether to continue or to stop programme
do {
j = 1;
cout << "Enter the min number of interval! ";
cin >> n;
cout << "Enter the max number of interval! ";
cin >> m;
if (n > m) { // Detects wether „n” is larger than „m”
cout << "Max number of interval has to be larger than min number!";
do { // If max number is larger than min number, screen is cleared
cin.clear();
cin.ignore();
cout << "Enter the numbers again!";
cout << "\n Enter the min number of interval! ";
cin >> n;
cout << "\n Enter the max number of interval! ";
cin >> m;
}
while (n > m);
}
cout << "Even numbers in given interval: ";
for (; n <= m; n++)
{
if (n % 2 == 0)
{ // Detects, wether there are even numbers in given interval
if (n != 0) {
cout << n << " ";
j *= n;
}
if ((n == m) && (n % 2 != 0)) {
j=0;
}
}
}
cout << "\n The product of found even numbers: " << j << " ";
cout << "\n Repeat? (Y/N) ";
cin >> answer;
system("cls");
}
while (tolower(answer) != 'n');
}
But I have a small problem, so I can't get the program 100% done because of the problem.
Like, user enters range, whose min and max number is the same and it's odd. In that case program has to print out a sentence "there were no even numbers in interval" in place of "The product of found even numbers:". I have searched the solution in internet, but haven't found it.
I hope you'll know the right solution.
Some hints to help you along the way: If there was no even number in the range, you will not enter into the loop. What will j be then? How do you react on that value?
I tried to fix your code, I did the best I could from what I understood you were tring to do.
I cleaned it up, fixed spelling and grammer, I deleted unnecessary stuff, I also made it more compact and nice to look at.
#include <iostream>
int main() {
int max=0, min=1, sum=0; product = 1, amount = 0; // max, min - entered by user, product - product of all even numbers in interval, sum - sum of all even numbers in interval. amount - amount of even numbers in interval
char x=Y; // Entered by user to know if to quit or continue to continue.
while ((x == Y) || (x == y))
{
while (min > max) { // System detects whether minimum is bigger than maximum
cin.clear(); // Clears screen so if this part runs again it wouldn't get messy.
cin.ignore();
cout << "Max has to be larger than min!";
cout << "\n Enter the min number of interval! ";
cin >> min;
cout << "\n Enter the max number of interval! ";
cin >> max;
}
for (; min <= max; min++)
{
if (min % 2 == 0)
{
sum+=n;
count++;
product*=n;
}
}
if (count == 0)
{
product=0;
cout << "There are no even numbers in interval!";
}
else
{
cout << "\n The amount of the even numbers in interval: " << amount << ",the product of the even numbers: " << product << ",the sum of the even numbers: " sum << "\n\n";
}
cout << "Repeat? (Y/N) ";
x=getchar;
system("cls");
}
return 0;
}

Trying to find the lowest number in my array, used the same line for highest number

Basically what I am trying to do is get the lowest number, but the program is feeding me back garbage, but I use the same line of code to get the highest value, only change I made was > to <, the program gives me back the highest value no problem put not the lowest. And I have tried everything I can think of from making the lowest= x[0], lowest=101( user is suppose to enter in grades on scale of 0-100, thought made it had something to do with the value. ) and lowest =highest and it still give me back a number like -9.255596e...., any help or suggestion or greatly appreciated, or maybe a point in the right direction just really trying to understand why it works for one set of numbers and not the others.
#include "stdafx.h"
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
double average(double,int);
double sum1(double[],int);
double highest(double[], int);
double lowest(double[], int);
int _tmain(int argc, _TCHAR* argv[])
{
double gradeBook[1000];
char x;
int count = 0;
cout << "Do you wish to start the program if so enter y to stop enter q" << endl;
cin >> x;
while (x != 'q')
{
cout << "Enter in test grade on a scale of 0 to 100" << endl;
cin >> gradeBook[count];
if (gradeBook[count]<0 || gradeBook[count]>100)
{
cout << " Please try again ";
count--;
}
else
cout << "valid answer" << endl;
count++;
cout << "Do you wish to continue entering in grades? If so enter y to stop enter q" << endl;
cin >> x;
}
highest(gradeBook, count);
cout << "The highest grade enter is " << highest(gradeBook, count) << endl;
lowest(gradeBook, count);
cout << "The lowest grade enter is " << lowest(gradeBook, count) << endl;
cout << lowest <<endl;
return 0;
}
double highest(double x[], int y)
{
double highest = 0;
for (int i = 0; i<= y; i++)
{
if (x[i]>highest)
highest = x[i];
}
return highest;
}
double lowest(double x[], int y)
{
double lowest = 100;
for (int i = 0; i<= y; i++)
{
if (x[i]< lowest)
lowest = x[i];
}
return lowest;
}
A way to resolve your question is to use code already tested.
In your case you can use min_element and max_element to find min and max element of your code:
cout << "The highest grade enter is " << *max_element(gradeBook,
gradeBook+count) << endl;

C++ Airfare Charge Calculation project

I have to create a program to calculate charges for airfare. It's a simple program so far and I am not done adding to it, but every time I run it the result turns out to be 0. Is there something missing in my code? I am a beginner and I would appreciate any advice on improving my code. Thank you.
#include <iostream>
using namespace std;
void main () {
int distance = 0;
int num_bags= 0;
int num_meals= 0;
double distance_price = distance * 0.15;
double bag_price = num_bags * 25.00;
double meal_price = num_meals * 10.00;
double total_airfare = 0.00;
cout << "CorsairAir Fare Calculator" << endl;
cout << "Enter the distance being travelled: " << endl;
cin >> distance;
cout << "Enter number of bags checked: " <<endl;
cin >> num_bags;
cout << "Enter the number of meals ordered: " << endl;
cin >> num_meals;
total_airfare = (distance_price + bag_price + meal_price);
cout << total_airfare;
}
Your confusion is completely understandable - the piece you're missing is that when you assign a variable, you're assigning the left side to the result of the right side at that moment in time. It's not like algebra, where you say f(x) = x + 5 and f(x) is always whatever x + 5 is.
So, you assign double distance_price = distance * 0.15 when distance is 0 (which you just initialized). distance_price remains 0 even after you ask for input and change distance.
Do your price calculations after you ask for input, and everything will work just fine.
You are calculating the distance_price bag_price meal_price with default values i.e. 0 not with the value which you took from user.
Below code works fine and you won't see the issue.
#include <iostream>
using namespace std;
// My compiler did not allow void main so used int main
int main () {
int distance = 0;
int num_bags= 0;
int num_meals= 0;
double distance_price ;
double bag_price ;
double meal_price;
double total_airfare;
cout << "CorsairAir Fare Calculator" << endl;
cout << "Enter the distance being travelled: " << endl;
cin >> distance;
cout << "Enter number of bags checked: " <<endl;
cin >> num_bags;
cout << "Enter the number of meals ordered: " << endl;
cin >> num_meals;
distance_price = distance * 0.15;
bag_price = num_bags * 25.00;
meal_price = num_meals * 10.00;
total_airfare = 0.00;
total_airfare = distance_price + bag_price + meal_price;
cout << total_airfare;
return 0;
}
Result
CorsairAir Fare Calculator
Enter the distance being travelled:
200
Enter number of bags checked:
2
Enter the number of meals ordered:
2
100

Unable to make program calculate correctly

I am trying to make a program which does a very basic calculation, but for some reason i can't get the code right. It is supposed to calculate the miles per gallon for one trip. You can then add this info multiple times (for different trips) and for each time it should calculate the total miles per gallon (i.e. the average miles per gallon of all the trips). This is the code:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int counter = 1;
double milePerRe, milePerTo = 0, x, y;
cout << "Enter the miles used (-1 to quit): ";
cin >> x;
cout << "Enter gallons: ";
cin >> y;
while (x != -1)
{
milePerRe = x/y;
milePerTo += milePerRe;
milePerTo /= counter;
cout << "MPG this tankful: " << setprecision( 6 ) << fixed << milePerRe;
cout << "\nTotal MPG: " << setprecision( 6 ) << fixed << milePerTo << endl << endl;
counter++;
cout << "Enter the miles used (-1 to quit): ";
cin >> x;
if (x != -1)
{
cout << "Enter gallons: ";
cin >> y;
}
}
system("pause");
return 0;
}
When I run the program and say I enter 10 on the miles and 1 on the number of gallons the first time and the second time, everything works fine. Then if i do it again a third time the calculations begin to become incorrect.
You can not calculate average of averages the way you do it. In your code you are dividing by the counter EACH iteration, while you should divide it only at the end.
Best way to do what you need is something like this:
...
double totalMiles = 0;
double totalGallons = 0;
...
while (x != -1)
{
milePerRe = x/y;
totalMiles += x;
totalGallons += y;
milesPerTo = totalMiles / totalGallons;
...
However, if your task was to explicitly calculate the average of trips (not the average of miles/gallons), you would need to introduce another variable, like this:
...
double currentMilesPerTo;
...
while (x != -1)
{
milePerRe = x/y;
milePerTo += milePerRe;
currentMilesPerTo = milePerTo/counter;
....
cout << "\nTotal MPG: " << currentMilesPerTo;
...
the value of x and y are not being updated properly i guess.after every iteration try to make x and y to zero.
hope it works this way
TNQ