C++ equation returns -nan(ind) - c++

So I'm writing code to semi-automatically solve (in)direct proportional questions using two values that are always given at the start. It's returning a -nan(ind) error so I'm hopefully seeking for someone to help. Thank you in advance, your help is always appreciated no matter how small it is.
I understand nan is not a number but it's just being irritating to fix this, not asking for someone to feed me the fix but if you'd like to you may - I'm looking to find a fix so that in the future I wouldn't be as clueless when it comes to an issue like this.
#include "Prop.h"
float c, d, k;
std::string prop::getinput(std::string obj) {
std::getline(std::cin, obj);
}
float prop::storefloat(float inp) {
std::cin >> inp;
return 1;
}
int prop::printarr(float arr[]) {
std::copy(arr, arr + sizeof(arr) / sizeof(arr[0]), std::ostream_iterator<float>(std::cout, "\n"));
}
int prop::compare(int com, int pare) {
if (com && pare <= 0) {
return 0;
}
}
void prop::direct(float a, float b, float constant) {
constant = DIRECTfindconstant(a, b);
printf("%d\n", constant);
c = ((constant) * (b));
printf("%d\n", c);
d = ((b) / (constant));
printf("%d\n", d);
std::cout << "Constant : " << constant << "\nDominant algebraic letter : " << c << "\nSecond Letter : " << d << "\n";
}
float prop::completedirect(float a, float b, float c) {
compare(a, b);
direct(a, b, c);
return 0;
}
float prop::DIRECTfindconstant(float a, float b) {
//k on bottom right, a ontop, b on bottom right
float k = ((a) / (b));
return k;
}
float prop::INDIRECTfindconstant(float a, float b) {
//k ontop, a on bottom left, b on bottom right
float k = a * b;
return k;
}
void prop::caseinput(int inp, float val, float val2) {
switch (inp) {
case Prop::proportionality::direct: {
float constant = DIRECTfindconstant(val, val2);
printf("%d\n", constant);
printf("%d", val);
printf("%d", val2);
completedirect(val, val2, constant);
break;
};
default:
break;
}
}
//prop.cpp
int main()
{
std::cin >> test;
pro->storefloat(a);
pro->storefloat(b);
pro->caseinput(test, a, b);
system("pause");
return 0;
}

Quoting the relevant part:
float prop::storefloat(float inp) {
std::cin >> inp;
return 1;
}
This is pass-by-value, as your book should tell you. You can change the local inp, but it does not affect the caller. The return value 1 is pointless here, while return values are the logical way to return a value to the caller.

Related

Odd function pointer segmentation fault [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I have to find the value of x such that f(x)=C, where f is a monotonically increasing function over the interval [a,b]. It has to have a logarithmic complexity so I've made this function which I believe to be correct:
double search(double a, double b, double c, double (*f)(double x)) {
double pivot;
do {
pivot = abs((a-b)/2);
if (abs((*f)(pivot) - c) < 0.001) { //f(x) == c
return pivot;
} else if ((*f)(pivot) > c) {
b = pivot;
} else {
a = pivot;
}
} while (abs(a-b) != 0);
return 0;
}
which works whenever I call it like this:
int main(void) {
double a = 0.0, b = 10.0, c = 5.0;
cout << search(a, b, c, func1) << endl;
return 0;
}
but if I change it to this (the value of b):
int main(void) {
double a = 0.0, b = 100.0, c = 5.0;
cout << search(a, b, c, func1) << endl;
return 0;
}
I get a segmentation fault when the function is called. What is going wrong here?
(I can see that the program crashes when the function is called when I use the VSCode debugger. Otherwise, when I just compile and run it, it seems to get stuck in an infinite loop or something i.e. it doesn't throw the segmentation fault error).
If needed, func1 simply does return 2 * x.
EDIT:
Here's the full .cpp file if someone needs it to reproduce:
#include <iostream>
using namespace std;
double func1(double x) {
return 2 * x;
}
double func2(double x) {
return x + 0.5;
}
double search(double a, double b, double c, double (*f)(double x)) {
double pivot;
do {
pivot = abs((b-a)/2);
if (abs((*f)(pivot) - c) < 0.1) { //f(x) == c
return pivot;
} else if ((*f)(pivot) > c) {
b = pivot;
} else {
a = pivot;
}
} while (abs(b-a) != 0);
return 0;
}
int main(void) {
double a = 0.0, b = 10.0, c = 5.0;
cout << search(a, b, c, &func1) << endl;
cout << search(a, b, c, func1) << endl;
return 0;
}
where changing the value of b to 100.0 will cause the fault to occur.
pivot = abs((a-b)/2); is wrong it as it computes half of the distance from a to b not the middle point of them, use:
pivot = abs((a-b)/2)+a; // provided that *a* is less than *b*

How can I get a function to read the next line of a document everytime it's called?

Really new programmer with a really bad professor here.
I have this code that is supposed to get inputs from a text document (inputsFile) using a function (get_coefficients) and do stuff with it. Currently, everything works perfectly except it reads the same line from the file every time it's executed in the while loop in main. I've google around but I can't find anything that is implementable in my case. I've tried implementing while loops and trying to pass some sort of counting variable but nothing seems to work.
Since this is an assignment for school, I can't do anything fancy. So the more elementary the explanation, the better please, haha. Thank you in advance for any help I get.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
//=======================================FUNCTIONS======================================
//a function that displays instructions
void display_instructions() {
cout << "Enter a, b, c: ";
}
//a function that gathers inputs
void get_coefficients(double& a, double& b, double& c) {
ifstream inputsFile;
string inputs;
string inputString;
inputsFile.open("textinputs.txt");
inputsFile >> a >> b >> c;
cout << a << b << c;
inputsFile.close();
}
//a function that calculates a discriminant
double calc_discriminant(double a, double b, double c) {
double discriminant = (b * b) - (4 * a * c);
return discriminant;
}
//a function that calculates root 1
double calc_root_1(double a, double b, double c, double disc) {
double r1 = ((-b) + (sqrt(disc))) / (2 * a);
return r1;
}
//a function that calculates root 2
double calc_root_2(double a, double b, double c, double disc) {
double r2 = ((-b) - (sqrt(disc))) / (2.0 * a);
return r2;
}
void display(double r1, double r2) {
cout << "the roots are " << r1 << " and " << r2 << "." << endl;
}
//=======================================EXCECUTE=======================================
int main()
{
//while again is true
for (int i = 0; i < 3; i++) {
double a, b, c;
display_instructions();
//run get numbers
get_coefficients(a, b, c);
//if discrimant less than 0 stop the program
if (calc_discriminant(a, b, c) < 0) {
cout << "No real solution" << endl;
}
else { //else get the roots
double disc = calc_discriminant(a, b, c);
double r1 = calc_root_1(a, b, c, disc);
double r2 = calc_root_2(a, b, c, disc);
//print the roots
display(r1, r2);
}
}
}
The problem here is that when you do inputsFile.open() you're opening the file from the start. You should only open the file once so each time you read from it you'll read the next line from where you were the last time. However, the ifstream will be deleted at the end of the scope if you don't save it anywhere. What you can do is initialize the ifstream in main() and then pass it to the function by reference so the ifstream will still be there until the program reaches the end of main.
I think this should work for what you want:
#include <iostream>
#include <fstream>
#include <string>
#include <math.h>
using namespace std;
//=======================================FUNCTIONS======================================
//a function that displays instructions
void display_instructions() {
cout << "Enter a, b, c: ";
}
//a function that gathers inputs
void get_coefficients(double& a, double& b, double& c, ifstream& inputsFile) {
string inputs;
string inputString;
inputsFile >> a >> b >> c;
cout << a << b << c;
}
//a function that calculates a discriminant
double calc_discriminant(double a, double b, double c) {
double discriminant = (b * b) - (4 * a * c);
return discriminant;
}
//a function that calculates root 1
double calc_root_1(double a, double b, double c, double disc) {
double r1 = ((-b) + (sqrt(disc))) / (2 * a);
return r1;
}
//a function that calculates root 2
double calc_root_2(double a, double b, double c, double disc) {
double r2 = ((-b) - (sqrt(disc))) / (2.0 * a);
return r2;
}
void display(double r1, double r2) {
cout << "the roots are " << r1 << " and " << r2 << "." << endl;
}
//=======================================EXCECUTE=======================================
int main()
{
ifstream inputsFile;
inputsFile.open("textinputs.txt");
//while again is true
for (int i = 0; i < 3; i++) {
double a, b, c;
display_instructions();
//run get numbers
get_coefficients(a, b, c, inputsFile);
//if discrimant less than 0 stop the program
if (calc_discriminant(a, b, c) < 0) {
cout << "No real solution" << endl;
}
else { //else get the roots
double disc = calc_discriminant(a, b, c);
double r1 = calc_root_1(a, b, c, disc);
double r2 = calc_root_2(a, b, c, disc);
//print the roots
display(r1, r2);
}
}
inputsFile.close();
}

Can you store arithmetic operators in an array i,e(+, -, *, /) in C++

I want to make a program that takes 4 numbers eg.(a, b, c and d) and checks if using arithmetic operators i can make the first 3 numbers result to the fourth number, like if the input is (3, 4, 5, 23) this will check out true because
3 + 4 * 5 = 23,So i want to make an array that has the operators and use a loop to check every possible combination, Hope i made it clear.
Edit:
Its actually codeforces problem, given 4 numbers. Check whether he could get the fourth number by using the arithmetic operators (+,−,×) between the other three numbers. Knowing that an operator can be used only once. in this format ->(a□b□c=d).My question was if there is a way to make it automatic or do i have to code every possibility manually So sorry for any confusion i may have caused.
You can't store the operators in an array, but you could make wrapper functions for them and store those in an array.
int add(int a, int b) {
return a + b;
}
int sub(int a, int b) {
return a - b;
}
int mul(int a, int b) {
return a * b;
}
int div(int a, int b) {
return a / b;
}
typedef int (*funptr)(int, int);
funptr arr[] = { add, sub, mul, div };
You can then call them like:
(arr[1])(2, 1) // call sub(2, 1)
The parentheses around arr[1] aren't needed in this case, but I like to put them for clarity.
No. You'd have to write a program to work this out. You could store something like function pointers to the arithmetic operators in an array, but I don't think that would help solve your problem. You'd still have to write the code to solve your problem.
Adding onto #CoffeeTableEspresso's answer, you can also put those function pointers into a map.
int add(int a, int b) {
return a + b;
}
int sub(int a, int b) {
return a - b;
}
int mul(int a, int b) {
return a * b;
}
int div(int a, int b) {
return a / b;
}
typedef int (*funptr)(int, int);
std::map<char,funptr> operators = {
{'+', add},
{'-', sub},
{'*', mul},
{'/', div}};
Then you can do
operators['+'](4,7);
Which might be a bit more readable, and you can iterate through these more easily.
I thought I would submit a compete answer. This works for positive numbers. It may take a bit more work to cover all the possibilities. And it does not answer to CoffeeTableEspresso's question about precedence. But it may help with your last question about if statements.
#include <iostream>
namespace {
auto add = [](int a, int b) {return a + b; };
auto sub = [](int a, int b) {return a - b; };
auto mult = [](int a, int b) {return a * b; };
auto divd = [](int a, int b) {return b ? a / b : -1; };
std::vector<int(*)(int, int)> ops = { add,sub,mult,divd };
}
int check(int* params)
{
for (size_t i = 0; i < 4; ++i)
for (size_t j = 0; j < 4; ++j)
{
auto result = ops[i](params[0], ops[j](params[1], params[2]));
if (params[3] == result)
return result;
else
std::cout << result << std::endl;
}
return -1;
}
int main()
{
int params[] = { 3, 4, 5, 23 };
std::cout << check(params);
}
Operators * / have a higher precedence than + -, so operator[i](A, operator[j](B, C)) solution doesn't really work.
You can write a little string calculator, and cycle through char-operators:
#include <iostream>
#include <sstream>
#include <vector>
#include <cmath>
double calculate(std::string str)
{
// calculator there
return -1;
};
int main()
{
std::vector<char> op = {'+', '-', '*', '/'};
std::vector<int> a = { 96, 3, 10, 42 };
for (auto op1: op)
for (auto op2: op)
{
std::stringstream ss;
ss << a[0] << op1 << a[1] << op2 << a[2];
double result = calculate( ss.str());
if (std::abs(a[3] - result) < 1E-6)
std::cout << ss.str() << " = " << a[3];
else
std::cout << ss.str() << " = " << result << " != " << a[3];
}
}

Returning and outputting 2 integers from 1 function

i have to write a code that has a function that takes two integers and returns x as (a + b) and y as (a * b) and when i run it, it only outputs y. Why doesnt it output (or return) x?
#include <iostream>
using namespace std;
int math (int a, int b) {
int x, y;
x = a + b;
y = a * b;
return x, y;
}
int main() {
cout << math (5,3);
getchar();
getchar();
return 0;
}
The return type of math is int, so this is what it returns (a single integer).
The expression x, y uses the comma operator. The comma operator evaluates x, discards its value, and then evaluates and returns y. In other words, return x, y is equivalent to return y.
You could use std::pair<int,int> to return a pair of integers.
The line
return x, y;
does not do what you expect. The comma operator returns only the value after the last comma - in this case, y. To return multiple values, you should use a struct or class containing both.
You can only return one thing. You can put those in a struct, and return it. Simpler example.
struct xy {
int x;
int y;
};
xy math(int a, int b) {
xy pair;
int x, y;
pair.x = a + b;
pair.y = a * b;
return pair;
}
There are two ways to make a function return more than one value. The
first is to use out parameters, either references or pointers:
void
math( int a, int b, int& sum, int& product )
{
sum = a + b;
product = a * b;
}
int
main()
{
int s;
int p;
math(5, 3, s, p);
std::cout << s << ' ' << p << std::endl;
return 0;
}
The other is to define a class to contain the two values:
struct MathResults
{
int sum;
int product;
};
MathResults
math( int a, int b )
{
return MathResults{ a + b, a * b };
}
std::ostream&
operator<<( std::ostream& dest, MathResults const& value )
{
dest << value.sum << ' ' << value.product;
}
int
main()
{
std::cout << math( 5, 3 ) << std::endl;
return 0;
}
In most cases, the second solution is to be preferred.

Using an input string as a function name c++

First time posting so be gentle. I've started to teach myself C++ as I've always had an interest and also it will be useful for work in the future.
Ok so i have written a very basic program that will either Add, Subtract, Multiply or Divide depending on the user input.
My question is can i use an input from the user as string and use that to call a function?
See code below:-
#include <iostream>
#include <string>
using namespace std;
// Addition Function
int Add (int a, int b)
{
int r; //Result
r=a+b; //formula
return r; //return result of formula
}
// Subtraction Function
int Subtract (int a, int b)
{
int r; //Result
r=a-b; //formula
return r; //return result of formula
}
// Multiply Function
int Multiply (int a, int b)
{
int r; //Result
r=a*b; //formula
return r; //return result of formula
}
// Divide Function
int Divide (int a, int b)
{
int r; //Result
r=a/b; //formula
return r; //return result of formula
}
// Main
int main()
{
int ip1, ip2, z;
string option;
cout << "Enter first number: ";
cin >> ip1;
cout << "Enter second number: ";
cin >> ip2;
cout << "What would you like to do?, Please type an option (Options: Add, Subtract, Multiply, Divide)\n";
getline(cin,option);
z = option (ip1,ip2);
cout << "The result is " << z;
}
So i ask the user to type in an option i.e. Add, the program then takes that string(Add) and uses it to call the Add function.
At the moment im getting a 'no match for call to '(std::string {aka std::basic_string}) (int&, int&)' error on compile
Any help would be appreciated
Thanks
Lewis
You can use a pretty simple if conditional tree:
if (option == "Add") z = Add(ip1, ip2);
else if (option == "Subtract") z = Subtract(ip1, ip2);
else if (option == "Multiply") z = Multiply(ip1, ip2);
else if (option == "Divide") z = Divide(ip1, ip2);
Alternatively you can use an std::map to map an std::string to the corresponding function pointer. It possibly cleaner but definitely longer to write:
std::map<std::string, std::function<int(int, int)>> mapping;
mapping["Add"] = &Add;
mapping["Subtract"] = &Subtract;
mapping["Multiply"] = &Multiply;
mapping["Divide"] = &Divide;
if (mapping.find(option) == mapping.end())
// there's no such an option
z = mapping[option](ip1, ip2);
In this particular case you can even do without std::function and just use C function pointers (for non-std::function lovers):
std::map<std::string, int(*)(int, int)> mapping;
On a side note, notice that you can get rid of a lot of lines of code and temporary variables in your function declarations:
int Add (int a, int b) { return a + b; }
int Subtract (int a, int b) { return a - b; }
int Multiply (int a, int b) { return a * b; }
int Divide (int a, int b) { return a / b; }