Help with absolute value and if statement


Hello guys. I am trying to write a script for a simple calculator. that does addition, subtraction, multiplication, division, power and absolute value.
I have got everything es=xcept for the absolute value.

Because I ask the user to input two numbers separated by a function.
absolute value must be entered as so: |YourNumber| and the operation must be performed and the result has to be a number with 2 decimal spaces.
I'm not sure how to have the program say the following.

If the first character entered starts with | and ends with | then perform the following operation.

abs(num1)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68

#include<iostream>                       //allows me to use cin and cout
#include<iomanip>                        // allows me to use the setprecision
#include<cmath>                          // to use pow() and fmod()
using namespace std;

int main()
{
double num1=0, num2=0;                  //These will be the numbers entered by the user
char function;                          //This is the variable that will register * / + - ^ % or negation
// This is my Header
	cout << setw(10) << left << "Course" << ":COSC 1436 Programming Fundamentals I" << endl;
	cout << setw(10) << left << "Subject" << ":Project I - Simple Calculator" << endl;
	cout << setw(10) << left << "Name" << ":Jose Abraham Garcia-Santos" << endl;
	cout << endl;
	cout << "This program will perform the \nactions of a simple calculator\n";
	cout <<"_______________________________________________________________"<< endl << endl << endl;

// This promts the user to make an operation.
	cout << "Enter two numbers, whole or decimals with 2 decimal places. \nThe numbers must be separated by the function you wish to execute." << endl;
	cin >> num1 >> function >> num2;


 // with the switch statement I am considering the possible inputs for the character variable function, in case by case.
//The switch will match the input to a case listed and will run the code below it. After that, it will break and skip
//the remainding cases and continue the code.
	switch (function)
	{
	case '+':
		cout << endl;
		cout << "The answer to (" << num1 << " " << function << " " << num2 << ") is:   " << fixed << showpoint << setprecision(2) << num1 + num2 << endl;
		break;
	case '-':
		cout << endl;
		cout << "The answer to (" << num1 << " " << function << " " << num2 << ") is:   " << fixed << showpoint << setprecision(2) << num1 - num2 << endl;
		break;
	case '*':
		cout << endl;
		cout << "The answer to (" << num1 << " " << function << " " << num2 << ") is:   " << fixed << showpoint << setprecision(2) << num1 * num2 << endl;
		break;
	case '/':
		cout << endl;
		cout << "The answer to (" << num1 << " " << function << " " << num2 << ") is:   " << fixed << showpoint << setprecision(2) << num1 / num2 << endl;
		break;
	case '^':
		cout << endl;
		cout << "The answer to (" << num1 << " " << function << " " << num2 << ") is:   " << fixed << showpoint << setprecision(2) << pow(num1, num2) << endl;
		break;
	case '%':
		cout << endl;
		//fmod(double x,double y) will work for decimals. % will only work for integers.
		cout << "The answer to (" << num1 << " " << function << " " << num2 << ") is:   " << fixed << showpoint << setprecision(2) << fmod(num1,num2) << endl; 
		break;

	default:
		// default case will run the following code if none of the cases listed are matched.
		cout << endl;
		cout << "You must enter an operation that contains a number, a function, and another number. Functions"<<endl;
		cout<<"you must use are [+],[-],[*],[/],[%],[^],[abs] and the numbers can be whole or decimal values." << endl;
		cout << "Please re-Run the program and try again." << endl;
		break;
		
	}

	system("pause");
	return 0;
}
Last edited on
Your input method is not practical for use with absolute value. How do you plan on getting the users input info for this? Currently the input in double char double. You need either char double char in the case of something like |-1| or double string for something like -1 abs.
Yes, I would like the user to input |Number|. The number has to be able to be a decimal and a negative.
but If I change the double char double to a char double char then the other operations will not perform if the user wishes to make them.
Last edited on
Hello cplusplusAbe,

I am not sure what you have in mind with abs(num1), but this form is for integers not doubles. Check out std::abs for std:complex:

http://www.cplusplus.com/reference/complex/abs/

This may not be as neat as entering three pieces on one line, but it does work if you enter "abs" for the function. Since function is defined as a "char" the cin >> function; will accept the "a" of "abs", but leaves the "bs\n" in the input buffer which needs to be cleared before the next input.

This will replace line 21 to catch "abs" and all you will need in the switch is a case for 'a' to deal with the "abs".

1
2
3
4
5
6
7
8
9
10
11
	cin >> num1;
	cin >> function;
	function = tolower(function);
	if (function == 'a')
	{  //  This line needed if a second number is needed. Or remove the else is a 2nd number is always needed.
	   // The input buffer needs cleared B4 the 2nd number is input.
		std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
		//cin >> num2; //  This line needed if 2nd number needed.
	}
	else
		cin >> num2;


Not sure if this is what you had in mind, but it does allow everything else to work. The bit of code could be enhanced a bit to let the user know what they are inputting.

Hope that helps,

Andy
Hi Andy, thank you.

Can you tell me what line 3 and line 7 do in your code?

I'm a little confused. I'm very new to this.
function = tolower(function);
Convert the character represented by the value of function to its' lowercase equivalent, and assign the result to function.

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Throw away all of the garbage input (through std::cin) until a newline is found.

More specifically,
Ignore (throw away) characters in the input sequence until
1. std::numeric_limits<std::streamsize>::max() characters have been thrown away; or
2. a newline ('\n') is reached.

std::numeric_limits<std::streamsize>::max()
Is the maximum possible number of characters that can fit in a stream.
Last edited on
I added this to my script, but after the newline user input is made, the program only returns my default cout statement in my switch function.

Hello cplusplusAbe,

Sorry for the delay, my internet was down most of yesterday.

Show me the changes you have made so I can figure out what is ging wrong.

Andy
Hello cplusplusAbe,

Earlier I made the statement "abs(num1), but this form is for integers not doubles." Somewhere I read or was lead to believe that "abs()" only worked with ints.

When researching "abs()" I found this web page: http://www.cplusplus.com/reference/cmath/abs/

which came from: http://www.cplusplus.com/reference/cmath/ and realized that with C++11 abs()" now works with doubles. And the function is overloaded to work with ints. Sorry for the confusion.

I have managed to get your program to work. Now we just have to figure out what you did differently.

Andy
Last edited on
Hi Andy, this is what i did.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87

#include<iostream>                       //allows me to use cin and cout
#include<iomanip>                        // allows me to use the setprecision
#include<cmath>                          // to use pow() and fmod()
#include<string>

using namespace std;

int main()
{
	double num1 = 0, num2 = 0;                  //These will be the numbers entered by the user
	char function;                         //This is the variable that will register * / + - ^ % or negation(absolute value)
// This is my Header
	cout << setw(10) << left << "Course" << ":COSC 1436 Programming Fundamentals I" << endl;
	cout << setw(10) << left << "Subject" << ":Project I - Simple Calculator" << endl;
	cout << setw(10) << left << "Name" << ":Jose Abraham Garcia-Santos" << endl;
	cout << endl;
	cout << "This program will perform the \nactions of a simple calculator\n";
	cout <<"_______________________________________________________________"<< endl << endl << endl;

// This promts the user to make an operation.
	cout << "Enter two numbers, whole or decimals with 2 decimal places. \nThe numbers must be separated by the function you wish to execute." << endl;
	cout << "If you wish to perform and absolute value, please enter it like so:  abs(YourNumber)  " << endl;

	// I want to create an if statement where if the first character typed is ( | ) then perform the following code for absolute value
	
	cin >> num1;
	cin >> function;
	function = tolower(function);
	if (function == 'a')
	{
		cin.ignore(numeric_limits < std::streamsize>::max(),'\n');
	}

	else
	cin >> num2;


// with the switch statement I am considering the possible inputs for the character variable function, in case by case.
//The switch will match the input to a case listed and will run the code below it. After that, it will break and skip
//the remaining cases and continue the code.


	switch (function)
	{
	case '+':
		cout << endl;
		cout << "The answer to (" << num1 << " " << function << " " << num2 << ") is:   " << fixed << showpoint << setprecision(2) << num1 + num2 << endl;
		break;
	case '-':
		cout << endl;
		cout << "The answer to (" << num1 << " " << function << " " << num2 << ") is:   " << fixed << showpoint << setprecision(2) << num1 - num2 << endl;
		break;
	case '*':
		cout << endl;
		cout << "The answer to (" << num1 << " " << function << " " << num2 << ") is:   " << fixed << showpoint << setprecision(2) << num1 * num2 << endl;
		break;
	case '/':
		cout << endl;
		cout << "The answer to (" << num1 << " " << function << " " << num2 << ") is:   " << fixed << showpoint << setprecision(2) << num1 / num2 << endl;
		break;
	case '^':
		cout << endl;
		cout << "The answer to (" << num1 << " " << function << " " << num2 << ") is:   " << fixed << showpoint << setprecision(2) << pow(num1, num2) << endl;
		break;
	case '%':
		cout << endl;
		//fmod(double x,double y) will work for decimals.

		cout << "The answer to (" << num1 << " " << function << " " << num2 << ") is:   " << fixed << showpoint << setprecision(2) << fmod(num1,num2) << endl; 
		break;
	case 'a':
			cout << "The answer to abs(" << num1 << ") is: " << abs(num1) << endl << endl;
			break;

	default:
		// default case will run the following code if none of the cases listed are matched.
		cout << endl;
		cout << "You must enter an operation that contains a number, a function, and another number. Functions"<<endl;
		cout<<"you must use are [+],[-],[*],[/],[%],[^],[ abs(YourNumber) ] and the numbers can be whole or decimal values." << endl;
		cout << "Please re-Run the program and try again." << endl;
		break;
		
	}
	
	return 0;
}
Hello cplusplusAbe,

You need to include the "limits" header file for line 32 to work.

After looking at the program for awhile I determined that line 32 is mostly pointless right now. If you wrap the bulk of the program in a "do while" loop to allow more than one execution of the program than line 32 will be useful. Either way it will not affect the program.

I ran the program here and after adding the "limits" header file it ran fine. Not sure what your problem is?

the "cout" on line 73 should look like line 70. The "fixed << setpersison(2)" part.

Hope that helps,

Andy
I just added the limits header file and added the fixed and set precision to my abs cout statement.

The program will compile but the issue is when I feed the input of :

abs(-45)

I should get a 45 in return. but I get
You must enter an operation that contains a number, a function, and another number. Functions
you must use are [+],[-],[*],[/],[%],[^],[ abs(YourNumber) ] and the numbers can be whole or decimal values.
Please re-Run the program and try again.
Press any key to continue . . .
Hello cplusplusAbe,

If you are trying to enter "abs(-45) [Enter] it will never work. The program works fine for me when I enter:

-45 [enter]
abs or just a [enter]


You might find this useful:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
	cout << "\n Num1: ";  // <--- Added
	cin >> num1;
	cout << "\n Function: ";  // <--- Added
	cin >> function;
	function = tolower(function);

	if (function == 'a')
	{  //  This line needed if a second number is needed. Or remove the else is a 2nd number is always needed.
	   // The input buffer needs cleared B4 the 2nd number is input.
		std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
		//cin >> num2; //  This line needed if 2nd number needed.
	}
	else
	{
		cout << "\n num2: ";  // <--- Added
		cin >> num2;
	}


Notice the cout statements I added.

Remember what you need to input and how your program works for that input.

Hope that helps,

Andy

Edit:

I just noticed that you have changed your instructions to the user. If you want the user to enter abs(YourNumber) That will take some work to rewrite the program to accept a string for the first input and then process that to get the number and "abs" for the function variable. A nice idea, but a hard way to go about it for input.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
#include <string>
#include <cctype>
#include <cmath>
#include <iomanip>

int main()
{
    std::cout << "Enter two numbers, whole or decimals with 2 decimal places. \n"
	         "The numbers must be separated by the function you wish to execute.\n"
	         "For absolute value, please enter it like so: abs(YourNumber)\n" ;

    double num1, num2 ;
    char function = std::cin.peek() ; // peek does not extract the character

    if( ( function = std::tolower(function) ) == 'a' ) // check for possible abs(...
    {
        std::string str ;
        std::getline( std::cin, str, '(' ) ; // read everything up to the ')', throw the ')' away

        if( str != "abs" ) function = '@' ; // input did not start with abs(, plant an invalid function
        else std::cin >> num1 ; // abs, only one number need to be read
    }

    else std::cin >> num1 >> function >> num2 ; // else read both numbers for + - * / or ^

    std::cout << std::fixed << std::showpoint << std::setprecision(2) ;

    if( function == 'a' ) // abs(num1)
         std::cout << "The answer to abs(" << num1 << ") is: " << std::abs(num1) << "\n\n";

    else // num1 operator num2
    {
        double result ;
        switch(function)
        {
            case '+' : result = num1 + num2 ; break ;
            case '-' : result = num1 - num2 ; break ;
            case '*' : result = num1 * num2 ; break ;
            case '/' : result = num1 / num2 ; break ;
            case '^' : result = std::pow( num1, num2 ) ; break ;
            default:
                // default case will run the following code if none of the cases listed are matched.
                std::cout << "\nYou must enter an operation that contains a number, a function, and another number.\n"
                             "Functions you must use are [+],[-],[*],[/],[%],[^],[ abs(YourNumber) ]"
                             " and the numbers can be whole or decimal values.\n"
                             "Please re-Run the program and try again.\n" ;
                return 1 ; // quit with non-zero exit code
        }

        std::cout << "\nThe answer to (" << num1 << ' ' << function << ' '
                  << num2 << ") is: " << result << '\n' ;
    }
}
Topic archived. No new replies allowed.