PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label calculator. Show all posts
Showing posts with label calculator. Show all posts

Monday, November 7, 2022

[FIXED] how do i make a console menu (c++) that i can return to after selecting something?

 November 07, 2022     c++, calculator, menu     No comments   

Issue

i made a simple menu and i know how to make choices and stuff but once i select a choice i don't know how to make it so that it returns to the selection menu.

#include <cmath>
#include <iostream>
#include <string>

int main()
{
    std::cout << "+====| LEO'S CALCULATOR |=========+\n\n";

    std::cout << "1 - Addition\n";

    std::cout << "2 - Subtraction\n";

    std::cout << "3 - Division\n";

    std::cout << "4 - circle area\n\n";

    std::cout << "+=================================+\n";

    int choice;

    std::cin >> choice;

    // CIRCLE RADIUS

    if (choice == 4)
    {

        std::cout << "what is the radius of your circle\n";
        double radius;
        double circleArea;
        const double pi = 3.14;
        std::cin >> radius;
        circleArea = pi * pow(radius, 2);
        std::cout << "the radius of your circle is: " << circleArea;
    }
}

I tried to look up what I was trying to do and i saw something regarding functions and being able to call them but i couldn't understand it. I tried to make the menu a function and in the choice i attempted to call said function but obviously it didn't work

im a beginner so if you have any other suggestions on what i should change id appreciate it and suggested resources for c++ are welcome


Solution

With a loop (do while for example) and an option to exit the loop.

#include <iostream>

int main()
{
    int choice;
    do
    {
        std::cout << "+====| LEO'S CALCULATOR |=========+\n\n";
        std::cout << "1 - Your menu...\n";
        std::cout << "5 - Quit\n\n";
        std::cout << "+=================================+\n";

        std::cin >> choice;

        // Your code.
    }
    while(choice != 5);
}


Answered By - CGi03
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, August 16, 2022

[FIXED] How would i create a price calculator with 1 input and 6 different outputs?

 August 16, 2022     calculator, html, input, output     No comments   

Issue

I have created an initial version, however you have to type the individual inputs for each output. I want to be able to just type into one input box and then it calculates all other outputs. How would i do this?

This is the code i have currently, im very very new to this :)

<form onsubmit="return false" oninput="o.value = (a.valueAsNumber /0.7).toFixed(0)" <br>
  NHS <input name="a" id="a" type="number" step="any" placeholder="NHS" <br> TO <input name="o" id="o" type="number" for="a" placeholder="RETAIL"></output> Retail


</form>

<form onsubmit="return false" oninput="o.value = (a.valueAsNumber *1).toFixed(0)" <br>
  NHS <input name="a" id="a" type="number" step="any" placeholder="NHS" <br> TO <input name="o" id="o" type="number" for="a" placeholder="Schools & CDC's"></output> Schools & CDC's


</form>

<form onsubmit="return false" oninput="o.value = (a.valueAsNumber / 0.7 -(a.valueAsNumber / 0.7 / 100*40)).toFixed(0)" <br>
  NHS <input name="a" id="a" type="number" step="any" placeholder="NHS" <br> TO <input name="o" id="o" type="number" for="a" placeholder="Trade - Band A" Math.round></output> Trade - Band A


</form>

<form onsubmit="return false" oninput="o.value = (a.valueAsNumber *1).toFixed(0)" <br>
  NHS <input name="a" id="a" type="number" step="any" placeholder="NHS" <br> TO <input name="o" id="o" type="number" for="a" placeholder="Trade - Band B"></output> Trade - Band B


</form>

<form onsubmit="return false" oninput="o.value = (a.valueAsNumber / 0.7 -(a.valueAsNumber / 0.7 / 100*20)).toFixed(0)" <br>
  NHS <input name="a" id="a" type="number" step="any" placeholder="NHS" <br> TO <input name="o" id="o" type="number" for="a" placeholder="Trade - Band C" Math.round></output> Trade - Band C


</form>

<form onsubmit="return false" oninput="o.value = (a.valueAsNumber / 0.7 -(a.valueAsNumber / 0.7 / 100*10)).toFixed(0)" <br>
  NHS <input name="a" id="a" type="number" step="any" placeholder="NHS" <br> TO <input name="o" id="o" type="number" for="a" placeholder="Trade - Band D" Math.round></output> Trade - Band D


</form>

https://jsfiddle.net/5gpLbj80/2/


Solution

First piece of advice would be to remove all of those inline event handlers. Attach a named function, then do all of your grunt-work inside it. By using addEventListener to connect the two, the function 'knows' which element it's attached to. That is to say, we can simply use this.value to get it's value, rather than having to use document.getElementById('nhs').value

"use strict;"
function byId(id){return document.getElementById(id)}
window.addEventListener('load', onLoaded, false);

function onLoaded(evt)
{
  let input = byId('myInput');
  input.addEventListener('input', onInputReceived, false);
}

function onInputReceived(evt)
{
  let outputs = [byId('output1'), byId('output2'), byId('output3')];
  let value = parseFloat(this.value);
  if (!isNaN(value))
  {
    outputs[0].textContent = value * 2;
    outputs[1].textContent = value * 3;
    outputs[2].textContent = parseInt( (value * 3)/4 );
  }
  else
  {
    outputs[0].textContent = 
    outputs[1].textContent = 
    outputs[2].textContent = "*invalid input (enter a number)*";
  }
}
<label>Enter data: <input id='myInput'/></label><br>
<ul>
  <li id='output1'></li>
  <li id='output2'></li>
  <li id='output3'></li>
</ul>

Alternate snippet

<!doctype html>
<html>
<head>
<script>
"use strict;"
function byId(id){return document.getElementById(id)}
window.addEventListener('load', onLoaded, false);

function onLoaded(evt)
{
  let input = byId('myInput');
  input.addEventListener('input', onInputReceived, false);
}

function onInputReceived(evt)
{
  let outputs = [byId('output1'), byId('output2'), byId('output3')];
  let value = parseFloat(this.value);
  if (!isNaN(value))
  {
    outputs[0].textContent = value * 2;
    outputs[1].textContent = value * 3;
    outputs[2].textContent = parseInt( (value * 3)/4 );
  }
  else
  {
    outputs[0].textContent = 
    outputs[1].textContent = 
    outputs[2].textContent = "*invalid input (enter a number)*";
  }
}
</script>
</head>
<body>
    <label>Enter data: <input id='myInput'/></label><br>
    <ul>
      <li id='output1'></li>
      <li id='output2'></li>
      <li id='output3'></li>
    </ul>
</body>
</html>


Answered By - enhzflep
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, August 11, 2022

[FIXED] How many operations can we do with an 8-digit (plus decimal) calculator?

 August 11, 2022     calculator, combinatorics, decimal, operation     No comments   

Issue

I have this model: a simple 8-digit display calculator (no memory buttons, no square root etc etc) has buttons (the decimal point does not count as a 'digit'): 10 buttons for integers 0 to 9, 1 button for dot (decimal point, so it can hold decimals, like from 0.0000001 to 9999999.9), 4 buttons for operations (+, -, /, *), and 1 button for equality (=). (the on/off button doesn't count for this question)

The question is two-fold: how many numbers can they be represented on the calculator's screen? (a math-explained solution would be appreciated) *AND if we have to make all 4 basic operations between any pair of 2 numbers, of the above calculated, how many operations would that be?

Thank you for your insight and help!


Solution

For part one of this answer, we want to know how many numbers can be represented on the calculator's screen.

Start with a simplified example and work up from there. Let's start with a 1-digit display. With this calculator, you can display the numbers from 0 to 9, and you can display each of those numbers with a decimal point either before the digit (making it a decimal), or after the digit (making it an integer). How many unique numbers can be made?

.0, .1, .2, .3, .4, .5, .6, .7, .8, .9, 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.

That's 20 possibilities with 1 repeat number makes 19 unique numbers. Let's find this result again, but using a mathematical approach that we can scale up to a larger number of digits.

Start by finding all the numbers 0 <= n < 1 that can be made. For the numbers to fit in that range, the decimal point must be before the first digit. We're still dealing with 1 digit, so there are 101 different ways to fill the calculator with numbers that are greater than or equal to 0, but less than 1.

Next, find all the numbers 1 <= n < 10 that can be made. To do this, you move the decimal point one place to the right, so now it's after the first digit, and you also can't allow the first digit to be zero (or the number will be less than 1). That leaves you 9 unique numbers.

[0<=n<1] + [1<=n<10] = 10 + 9 = 19

Now we have a scaleable system. Let's do it with 2 digits so you see how it works with multiple digits before we go to 8 digits. With 2 digits, we can represent 0-99, and the decimal point can go in three different places, which means we have three ranges to check: 0<=n<1, 1<=n<10, 10<=n<100. The first set can have zero in its first place, since zero is in the set, but every other set can't have zero in the first place or else the number would be in the set below it. So the first set has 102 possibilities, but each of the other sets has 9 * 101 possibilities. We can generalize this by saying that for any number d of digits that our calculator can hold, the set 0<=n<1 will have 10d possibilities, and each other set will have 9 * 10d-1 possibilities

So for 2 digits:

[0<=n<1] + [1<=n<10] + [10<=n<100] = 100 + 90 + 90 = 280

Now you can see a pattern emerging, which can be generalize to give us the total amount of unique numbers that can be displayed on a calculator with d digits:

Unique displayable numbers = 10d + d * 9 * 10d-1

You can confirm this math with a simple Python script that manually finds all the unique numbers that can be displayed, prints the quantity it found, then also prints the result of the formula above. It gets bogged down when it gets to higher numbers of digits, but digits 1 through 5 should be enough to show the formula works.

for digits in range(1, 6):
    print('---%d Digits----' % digits)
    numbers = set()
    for d in range(digits + 1):
        numbers.update(i / 10**d for i in range(10**digits))
    print(len(set(numbers)))
    print(10**digits + digits * 9 * 10**(digits - 1))

And the result:

---1 Digits----
19
19
---2 Digits----
280
280
---3 Digits----
3700
3700
---4 Digits----
46000
46000
---5 Digits----
550000
550000

Which means that a calculator with an 8 digit display can show 820,000,000 unique numbers.

For part two of this answer, we want to know if we have to make all 4 basic operations between any pair of 2 numbers, of the above calculated, how many operations would that be?

How many pairs of numbers can we make between 820 million unique numbers? 820 million squared. That's 672,400,000,000,000,000 = 672.4 quadrillion. Four different operations can be used on these number pairs, so multiply that by 4 and you get 2,689,600,000,000,000,000 = 2.6896 quintillion different possible operations on a simple 8 digit calculator.

EDIT:

If the intention of the original question was for a decimal point to not be allowed to come before the first digit (a decimal 0<=n<1 would have to start with 0.) then the formula for displayable numbers changes to 10d + (d - 1) * 9 * 10d-1, which means the amount of unique displayable numbers is 730 million and the total number of operations is 2.1316 quintillion.



Answered By - schwartz721
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, July 19, 2022

[FIXED] how to make cin only take integer inputs

 July 19, 2022     c++, calculator, integer     No comments   

Issue

i new to programming and we are required to create a program that dont exit when the user inputs the wrong input, but i only learned the basics so far.. i already solved when the number is above and below 100 but when the user accidentally inserted a non integer it will go into a error loop. btw this is an average calculator.

#include <iostream>

using namespace std;

int main()
{
    int num[100];
    int n;
    double sum, average;

    cout << "how many numbers will you input?: ";
    cin >> n;

    while ( n > 100 || n <= 0 )
    {
        cout << "Error! number should in range of (1 to 100) only." << endl;
        cout << "Enter the number again: ";
        cin >> n;
    }

    for ( int i = 0; i < n; ++i )
    {
        cout << i + 1 << ". Enter number: ";
        cin >> num[i];
        sum += num[i];
    }

    average = sum / n;
    cout << "Average = " << average;
}

Solution

If std::istream::operator >> fails, it will set failbit. Therefore, you should check failbit (for example by calling std::cin.fail()) to see whether the conversion was successful, before using the result of the conversion.

If the conversion fails due to bad input, then the next call to std::istream::operator >> will automatically fail due to failbit being set. That is why you are getting stuck in an infinite loop. If you want to attempt input again after a conversion failure, you will first have to clear failbit, by using the function std::cin.clear().

Also, you will have to discard the bad input that caused the conversion to fail, because otherwise, the next time you call std::istream::operator >>, the conversion will fail again for the same reason. In order to clear the bad input, you can use std::cin.ignore(), like this:

std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );

In order to use std::numeric_limits, you will have to #include <limits>.

After performing these fixes on your code, it should look like this:

#include <iostream>
#include <limits>

using namespace std;

int main()
{
    int num[100];
    int n;
    double sum, average;
    bool input_ok;

    //repeat until input is valid
    do
    {
        cout << "How many numbers will you input? ";
        cin >> n;

        if ( cin.fail() )
        {
            cout << "Error: Conversion to integer failed!\n";

            input_ok = false;
        }
        else if ( n > 100 || n <= 0 )
        {
            cout << "Error: Number should in range of (1 to 100) only!\n";
            input_ok = false;
        }
        else
        {
            input_ok = true;
        }

        //clear failbit
        cin.clear();

        //discard remainder of line
        cin.ignore( numeric_limits<streamsize>::max(), '\n' );
    } while ( !input_ok );

    for ( int i = 0; i < n; ++i )
    {
        do
        {
            cout << i + 1 << ". Enter number: ";
            cin >> num[i];

            if ( cin.fail() )
            {
                cout << "Error: Conversion to integer failed!\n";

                input_ok = false;
            }
            else
            {
                input_ok = true;
            }

            //clear failbit
            cin.clear();

            //discard remainder of line
            cin.ignore( numeric_limits<streamsize>::max(), '\n' );
        } while ( !input_ok );

        sum += num[i];
    }

    average = sum / n;
    cout << "Average = " << average;
}

This program has the following behavior:

How many numbers will you input? 200
Error: Number should in range of (1 to 100) only!
How many numbers will you input? -31
Error: Number should in range of (1 to 100) only!
How many numbers will you input? test
Error: Conversion to integer failed!
How many numbers will you input? 4abc
1. Enter number: 1
2. Enter number: 2
3. Enter number: 3
4. Enter number: 4
Average = 2.5

As you can see, the program now works in that it can now handle bad input such as test. It rejects that input and reprompts the user for new input.

However, one problem with this program is that it accepts 4abc as valid input for the number 4. It would probably be appropriate to reject such input instead. One way to fix this would be to inspect the remainder of the line, instead of simply discarding it.

Another issue is that this solution contains a lot of code duplication. Apart from the range check, both do...while loops are nearly identical. Therefore, it would be better to put this loop into a function, which can be called from several places in your code.

However, I generally don't recommend that you use std::istream::operator >>, because its behavior is not always intuitive. For example, as already pointed out above:

  1. It does not always read a whole line of input, so that you must explicitly discard the remainder of the line.
  2. It accepts 4abc as valid input for the number 4.

In my experience, if you want proper input validation of integer input, it is usually better to write your own function that reads a whole line of input using std::getline and converts it with std::stoi. If the input is invalid, then the function should automatically reprompt the user.

In my example below, I am calling this function get_int_from_user.

If you want to additionally ensure that the input is in a certain range, then you can call the function get_int_from_user in an infinite loop, and break out of that loop once you determine that the input is valid.

#include <iostream>
#include <string>
#include <sstream>
#include <cctype>

int get_int_from_user( const std::string& prompt );

int main()
{
    int nums[100];
    int n;
    double sum;

    //repeat loop forever, until input is good
    for (;;) //equivalent to while(true)
    {
        n = get_int_from_user( "How many numbers will you input? " );

        if ( 1 <= n && n <= 100 )
            //input is good
            break;

        std::cout << "Error! Number should in range of (1 to 100) only.\n";
    }

    //read one number per loop iteration
    for( int i = 0; i < n; i++ )
    {
        std::ostringstream prompt;

        prompt << "Enter number #" << i + 1 << ": ";

        nums[i] = get_int_from_user( prompt.str() );

        sum += nums[i];
    }

    std::cout << "Average: " << sum / n << '\n';
}

int get_int_from_user( const std::string& prompt )
{
    std::string line;
    std::size_t pos;
    int i;

    //repeat forever, until an explicit return statement or an
    //exception is thrown
    for (;;) //equivalent to while(true)
    {
        //prompt user for input
        std::cout << prompt;

        //attempt to read one line of input from user
        if ( !std::getline( std::cin, line ) )
        {
            throw std::runtime_error( "unexpected input error!\n" );
        }

        //attempt to convert string to integer
        try
        {
            i = std::stoi( line, &pos );
        }
        catch ( std::invalid_argument& )
        {
            std::cout << "Unable to convert input to number, try again!\n";
            continue;
        }
        catch ( std::out_of_range& )
        {
            std::cout << "Out of range error, try again!\n";
            continue;
        }

        //The remainder of the line is only allowed to contain
        //whitespace characters. The presence of any other
        //characters should cause the entire input to get rejected.
        //That way, input such as "6sdfj23jlj" will get rejected,
        //but input with trailing whitespace will still be accepted
        //(just like input with leading whitespace is accepted by
        //the function std::stoi).
        for ( ; pos < line.length(); pos++ )
        {
            if ( !std::isspace( static_cast<unsigned char>(line[pos]) ) )
            {
                std::cout << "Invalid character found, try again!\n";

                //we cannot use "continue" here, because that would
                //continue to the next iteration of the innermost
                //loop, but we want to continue to the next iteration
                //of the outer loop
                goto continue_outer_loop;
            }
        }

        //input is valid
        return i;

    continue_outer_loop:
        continue;
    }
}

This program has the following behavior:

How many numbers will you input? 200
Error! Number should in range of (1 to 100) only.
How many numbers will you input? -31
Error! Number should in range of (1 to 100) only.
How many numbers will you input? test
Unable to convert input to number, try again!
How many numbers will you input? 4abc
Invalid character found, try again!
How many numbers will you input? 4
Enter number #1: 1
Enter number #2: 2
Enter number #3: 3
Enter number #4: 4
Average: 2.5

As you can see, it now correctly rejects the input 4abc.

I believe that using the function get_int_from_user makes the code in main much cleaner.

Note that the code above uses one goto statement. Under most circumstances, you should avoid using goto, but for breaking out of nested loops, it is considered appropriate.



Answered By - Andreas Wenzel
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing