Need to do compare without functions by using 3 variables on - c++

Need to do compare without functions. I gotta do compare by using function just once and use no more 3 variables. Task that I got: need to tabulate (A to B, with h step) and show local minimum by “*”
——————————
#include <iostream>
#include "clocale"
#include "cmath"
#include <iomanip>
using namespace std;
// ------------------------- f(x) = x*sin(3*x) - 1 -------------------
double f(double x){
return x*sin(3*x) - 1;
}
// -------------------------------------------------------------------------------
int main()
{
setlocale(LC_ALL, "russian");
double A,B;
double h;
// ------------------ ---------------------
cout << "A = ";
cin >> A;
cout << "B = ";
cin >> B;
cout << "h = ";
cin >> h;
// ------------------------------------------------------
cout.setf(ios_base::fixed);
cout.precision(4);
for (double k=A; k<=B; k+=h){
if (f(k - h) >= f(k) && f(k + h) >= f(k)){
cout << "*";
}
else{
cout << " ";
}
cout << "x = " << k << " y = " << f(k) << "\n";
}
system("pause");
return 0;
}

I hope I guess right what you want to do. For each f(x) you want to compare that value to f(x-h) and f(x+h) to see if f(x) is a local minimum. You seem to have something, but you are recalculating f(x-h), f(x) and f(x+h) every time you use the value, when in fact on each iteration you only need to compute a single new value.
Just remember previous values. Note that the first point you can compare previous and next value is A+h, hence we start with
auto current = f(A+h);
auto previous = f(A);
auto next = f(A+2*h);
if (do the comparison of current vs previous and next) print something
// now the loop
for (double x = A+2*h; x < B; x+=h){
previous = current;
current = next; // in the first iteration this is f(A+2*h)
next = f(x+h);
if (do the comparison of current vs previous and next) print something
}
Note that now in each iteration only the next value is calculated, while current and previous are already known from the iteration before.

since you are trying to find local minima then you should try following code. this is exactly as you wanted but more robust.
#include <iostream>
#include "clocale"
#include "cmath"
#include <iomanip>
using namespace std;
// ------------------------- f(x) = x*sin(3*x) - 1 -------------------
double f(double x){
return x*sin(3*x) - 1;
}
// -------------------------------------------------------------------------------
bool is_minima(double a, double b, double c){
if(a > b && c > b){
return true;
else
return false;
}
int main()
{
setlocale(LC_ALL, "russian");
double A,B;
double h;
// ------------------ ---------------------
cout << "A = ";
cin >> A;
cout << "B = ";
cin >> B;
cout << "h = ";
cin >> h;
// ------------------------------------------------------
cout.setf(ios_base::fixed);
cout.precision(4);
for (double k=A; k<=B; k+=h){
if (is_minima(f(k-h),f(k),f(k+h))){
cout << "*";
}
else{
cout << " ";
}
cout << "x = " << k << " y = " << f(k) << "\n";
}
system("pause");
return 0;
}

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();

C++ : How to use a pointer in an if statement condition

I am writing a program that takes in 3 user inputted values for a quadratic equation, does some calculation, and returns how many roots the quadratic has.
When I print *(point), it gives me the correct value from the function.
However, when I use *(point) in the If conditions, it does not seem to work the way I want it to - I believe that *(point)is always some positive number, hence why it always executing that specific if condition.
The user values: a = 9, b = -12, c = 4 should print out This quadratic has 1 root. and the values: a = 2, b = 16, c = 33 should print out This quadratic has 2 roots. BUT the program always prints out This quadratic has 0 roots. no matter what the values entered.
Here is my code:
#include "stdafx.h"
#include <iostream>
using namespace std;
float *quadratic(float a1[]);
int main()
{
float a1[3] = {};
float *point;
cout << "Enter a: ";
cin >> a1[0];
cout << "\nEnter b: ";
cin >> a1[1];
cout << "\nEnter c: ";
cin >> a1[2];
point = quadratic(a1);
cout << endl << "d = " << *(point) << endl;
if (*(point) < 0) {
cout << "\nThis quadratic has 2 roots.\n";
}
else if (*(point) > 0) {
cout << "\nThis quadratic has 0 roots.\n";
}
else { //else if *(point) is equal to 0
cout << "\nThis quadratic has 1 root.\n";
}
return 0;
}
float *quadratic(float a1[]) {
float d;
d = (a1[1] * a1[1]) - (4 * a1[0] * a1[2]);
float xyz[1] = { d };
return xyz;
}
Your function quadratic returns a pointer to a local array. After the function return that array doesn't exist anymore. The pointer is then a dangling pointer, a pointer pointing to a place in memory that has once held an object, but that now may hold anything or just rubbish.
Since the array that quadratic attempts to return is always one value there is no need for returning an array. Just return that value.
You don't even need to deal with arrays for the polynomial's coefficients, since they're always three, but if array seems better than individual a, b and c variables, then just use std::array, e.g. like this:
#include <iostream>
#include <array>
#include <vector>
using namespace std;
using Float = double;
auto square_of( Float const v ) -> Float { return v*v; }
auto determinant( array<Float, 3> const& a )
-> Float
{
return square_of( a[1] ) - 4*a[0]*a[2];
}
auto main()
-> int
{
array<Float, 3> a;
cout << "Enter A: "; cin >> a[0];
cout << "Enter B: "; cin >> a[1];
cout << "Enter C: "; cin >> a[2];
Float const d = determinant( a );
cout << "d = " << d << endl;
if( d < 0 )
{
cout << "This quadratic has 2 roots." << endl;
}
else if( d > 0 )
{
cout << "This quadratic has 0 roots." << endl;
}
else // d == 0
{
cout << "This quadratic has 1 root.";
}
}
The code above is equivalent to what I perceived as the intent of your code.
However, I'd check out the formula for roots of quadratic equations, and test the program, before handing in something.

How to calculate the true square root of a number with 3 user-defined functions

I need a bit of help and some tips on where to go
For a programming assignment, I have to write a program that calculates the square root of the number that the user inputs and there are certain requirements.
The main asks for the number and displays it, operates inside a Loop so that the user can repeat the program without closing it
The calculation has to be done in a function called sqRoot which will be called by main using the algorithm:
newValue = 0.5 * (oldValue + (X / oldValue))
sqRoot will need to find the absolute value of the number with a function named absVal which will then be called by sqRoot
I dont even know where to start with a program like this. But, this is what i have so far:
#include <iostream>
#include <cmath>
#include <cstdlib>
using namespace std;
double sqRoot();
double absVal();
int i = 0;
double X;
int main()
{
sqRoot = sqrt(X);
double X;
// Calculations
cout << "Please enter a number: ";
cin >> X;
while (X <= 0)
{
cout << "*** Error: Invalid Number! *** " << endl;
cout << "Please enter a number: ";
cin >> X;
}
while (X >= 1)
{
cout << "The Square Root is: " << sqRoot << endl;
}
}
double sqRoot ()
{
double newValue;
double oldValue ;
while (abs(newValue - oldValue) > 0.0001)
{
newValue = 0.5 * (oldValue + ( X / oldValue));
oldValue = newValue;
cout << " The square root is: " << newValue << endl;
}
return (newValue);
}
I'm just stuck with what to do next and how to properly write the program.
Thank You for the help and tips!
In your snippet you don't show how you implement absVal(), which is trivial:
double absVal( double x )
{
return x < 0.0 ? -x : x;
}
Assuming that you you know the ternary operator. Otherwise use an if.
The implementation of main() you posted is basically an infinite loop which calculates and prints repeatedly only the first number equal or greater then 1.0 that the user inputs. That's not what you are asked for, I think
I'm not sure if the x >= 1 condition is mandatory (tiny values requires more iterations) or an assumption of yours and what you are supposed to do in case of a negative number (you can use absVal instead of printing an error), but you can write something like this:
#include <iostream>
// #include <cmath> <-- you are not supposed to use that
// #include <cstdlib> <-- why do you want that?
// using namespace std; <-- bad idea
using std::cin;
using std::cout;
double absVal( double x );
double sqRoot( double x );
int main()
{
double num;
cout << "This program calculate the square root of the numbers you enter.\n"
<< "Please, enter a number or something else to quit the program:\n";
// this will loop till std::cin fails
while ( cin >> num )
{
if ( num < 0.0 ) {
cout << "*** Error: Invalid input! ***\n"
<< "Please enter a positive number: ";
continue;
}
cout << "The square root of " << num << " is: " << sqRoot(num);
cout << "\nPlease enter a number: ";
}
return 0; // you missed this
}
Then, in your implementation of sqRoot() you forgot to pass the variable x as a parameter, to initialize oldValue and newValue and if the flow of execution happens to enter the while loop it will exit after the first loop because oldValue = newValue; is evaluated before the condition. Try something like this (I used the relative error instead of the absolute difference to gain better precision with small values of x at the cost of more iterations):
double sqRoot(double x)
{
const double eps = 0.0001;
double newValue = 0;
double oldValue = x;
while ( oldValue != 0.0 )
{
newValue = 0.5 * (oldValue + (x / oldValue));
// check if the relative error is small enough
if ( absVal(newValue - oldValue) / oldValue < eps )
break;
oldValue = newValue;
}
return newValue;
}
Hope it helped.
Just a few corrections
#include <iostream>
#include <cmath>
#include <cstdlib>
using namespace std;
double sqRoot(double X);
int main()
{
double X;
// Calculations
cout << "Please enter a number: ";
cin >> X;
while (X <= 0)
{
cout << "*** Error: Invalid Number! *** " << endl;
cout << "Please enter a number: ";
cin >> X;
}
while (X >= 1)
{
cout << "The Square Root is: " << sqRoot(X) << endl;
}
}
double sqRoot(double X)
{
double newValue = 0;
double oldValue = X;
while (true)
{
newValue = 0.5 * (oldValue + (X / oldValue));
if (abs(newValue - oldValue) < 0.0001)
break;
oldValue = newValue;
//cout << " The square root is: " << newValue << endl;
}
return (newValue);
}

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++ Division . seemingly simple thing driving me crazy, advice please

Ok i've been programming for about a week now, i started with c++. I'm writing a program that is a kind of an arithmetic trainer, you enter the amount of equations you want, you enter your limit for the random number generator, you specify what kind of equations you want(/*-+), then the program uses a for loop and goes through and generates the equations and their answers in a var and then the users input is checked against this var and if they match another var which is counting the right answers is incremented. After the last equation the program tells the user how many they got right out of how many equations, and by dividing the amount of right answers by the amount of questions then multiplying this value by 100 u should obtain the accuracy percentage for this users arithmetic session. Problem is c++ keeps returning to me a friggin 0 value and i cannot for the life of me work out why in the world c++ is doing this.
entire program:
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;
void menu(void);
class session{
public:
session(){
create_session();
}
void create_session(void){
amount = 0;
range_limit = 0;
rights = 0;
answer = 0;
input = 0;
type = "";
while(amount == 0){
cout << "\nHow many equations do you want?: "; cin >> amount;
if(amount < 1){
cout << "\nAmount is too low!";
amount = 0;
}
}
while(range_limit == 0){
cout << "Enter the number range limit: "; cin >> range_limit;
if(range_limit < 1){
cout << "\nRange limit too low!";
range_limit = 0;
}
}
while(type == ""){
cout << "What equation type do you want?: "; cin >> type;
int strlen = type.size();
if(strlen < 1){
cout << "Invalid type input!";
type = "";
}
}
if(type == "+"){
for(int i=0;i<amount;i++){
int a = random();
int b = random();
answer = a + b;
cout << "\n" << a << " + " << b << " = "; cin >> input;
if(answer == input){
rights++;
}
}
}
cout << "\nYou got " << rights << " answers right out of " << amount << " equations." << endl;
cout << "Accuracy percentage: " << getAccuracy() << "%" << endl;
int post_menu=0;
while(post_menu == 0){
cout << "Enter 1 to create another session or 2 to return to the menu: ";
cin >> post_menu;
if(post_menu == 1){
create_session();
}else if(post_menu == 2){
menu();
}else{
cout << "Invalid input: ";
post_menu = 0;
}
}
}
float getAccuracy(){
float x = (rights/amount)*100;
return x;
}
int random(){
int x = 1+(rand()%range_limit);
return x;
}
void set_amount(int a){
amount = a;
}
void set_range_limit(int r){
range_limit = r;
}
void set_rights(int R){
rights = R;
}
void set_answer(int a){
answer = a;
}
void set_input(int i){
input = i;
}
void set_type(string t){
type = t;
}
private:
int amount;
int accuracy;
int range_limit;
int rights;
int answer;
int input;
string type;
};
int main(){
cout << "=== WELCOME TO ARITH! === \n=========================\n";
menu();
return 0;
}
void menu(void){
//Set the seed for random number gen.
srand(time(0));
//Set var for getting menu input, then get the menu input..
int menu_input;
cout << "\n[1]Create a Session. [2]Exit Arith. \nWhat would you like to do?: ";
cin >> menu_input;
//Now we check what the user wants and act accordingly..
if(menu_input > 2){
cout << "error";
menu_input=0;
}else if(menu_input == 1){
session start;
}else if(menu_input == 2){
cout << "\nExiting Arith!";
}else{
cout << "error";
menu_input=0;
}
}
Troublesome part:
float getAccuracy(){
float x = (rights/amount)*100;
return x;
some how the program is returning 0%.
anyone know why this is so and how to get the result im after.
rights and amount both are int , so when you divide the value is floored, for example if you do 5/2 the answer would be 2 instead of 2.5. To solve this you need to cast one of the variable to float like this: (float(rights)/amount) * 100.
when two int numbers are divided the result will also be int even if temporary variable. so you can make any of the variable float or double or cast it.
You need to convert only one data type because the other will be type promoted implicitly.
float x = ((double)rights/amount)*100;
or you can make your amount variable float by default if it doesnt affect any other part of your code.
Also you have the option to static cast:
float x = (static_cast<double>(rights)/amount)*100;