Here is the problem I must do(Just for context): Write a program that will input 2 integers from the user, will then calculate the first to the power of the second and then output the result. The Input, calculation and output should be in three separate subprograms/functions. You must calculate the exponentiation using a WHILE loop and multiplying the first number, the required number of times. For this homework only, you are allowed to use global variables to move information between functions.
Here is my code:
#include <iostream>
#include <cmath>
using namespace std;
double a, b, ans;
int main()
{
cout << "Please enter two whole numbers: ";
cin >> a >> b;
cout << conclusion() << calc();
system("pause");
return 0;
}
int calc()
{
double ans = pow(a, b);
return 0;
}
int conclusion()
{
cout << a << " To the power of " << b
<< " is " << ans;
return 0;
}
So here's what I'm having an issue with, I do online classes. The dude is like, "here's a problem, figure it out and just do it." Which is fine I guess, but when things like this come up its hard to find certain tutorials and questions. Anyway, I got my BASE code down. Now I need a while loop, and have no idea what this means: calculate the exponentiation using a WHILE loop and multiplying the first number, the required number of times.
I figured I could just do a while and do
double ans = pow(a, b);
But that's not the case apparently. That's what my chapter taught me, but not with a while and all this extra stuff you need to do for this. I asked a classmate, she said she had a really difficult time as well, and her example to me was:
int a = 0;
int b = 0;
int c = 1;
cin >> a;
cin >> b;
int powerOp(int a, int b, int c)
{
while (b > 0)
{
c = c * a;
b--;
}
cout << c;
return c;
}
I have been working almost all day and can't figure this out. I don't understand why we need to factorize and set the int = 1. I thought it could simply be
double ans = pow(a, b); //a and b being the 2 numbers the user inputs
Its pretty simple, lets say you have 2^3. You and I both agree that it is the same as doing 2x2x2. You mutiplied you first number A by itself B (your second number) times. Now for your loop, what you want have your second number server as your counter AND loop exit condition. Something like this
double YourPowerFunction(int a, int b)
{
int counter = 0;
double result = 1;
while (counter < b)
{
counter++:
result = result * a;
}
return result;
}
Okay so I'm pretty sure I found the answer. Result is the variable for ans
int calc() //function for calculation
{
//Still not sure how I did this one, after hours of playing around with it
while (b > 0) //This code is adding a 0 in the result. I can't figure it out
{
result = result * a;
b--;
}
return (result);
}
This is just a simple solution, as it wants to add a 0 in the end result.
Related
Find below my implementation for binary exponentiation
#include<iostream>
#include<cmath>
using namespace std;
int fast_exponentiation(int base, int pow) {
unsigned int result; // variable to store intermediaries
if (pow == 1) {
return base;
}
else if (pow == 0) {
return 1;
}
result = fast_exponentiation(base, floor(pow/2));
// even power
if (pow % 2 == 0) {
return result * result;
}
// odd power
else {
return result * base * result;
}
}
int main() {
int num, answer, p;
cout << "Enter the base: ";
cin >> num;
cout << "Enter power: ";
cin >> p;
answer = fast_exponentiation(num, p);
cout << answer << endl;
return 0;
}
The problem is when I ran this for inputs num= 3 and pow = 20 I get -808182895, a negative number. I can't seem to figure out what is wrong with the code? Can I get some help?
Value of 3^20 exceeds max possible int value 2^31, so you have got overflow. The simplest way to overcome this limit is using long long data type to provide possiblity for calculations upto power 39 (near 2^63)
For larger powers one need long number arithmetics - boost multi-precision, GMP etc
I need to count how many cubes of values between a and b (2 and 9 in this example) end with numbers between 2 and 5. Everything has to be done with recursion.
The output of this code is
part c = recc = 4
32767
0
It does not make sense to me. It calculates the value of n correctly, but then once asked to return it, returns either 0 or 32767, as if it was not defined.
Can anyone pinpoint the issue?
#include <iostream>
#include <string>
using namespace std;
void partb(int a, int b){
if(a<=b){
int p = (a*a*a)%10;
else if(p>=2 && p<=5){
cout<<a*a*a<<" ";
}
partb(a+1, b);
}
}
int recc(int n, int a, int b){
int p = (a*a*a)%10;
if(a>b){
cout<<"recc = " << n << endl;
return n;
}
else if(a<=b){
if(p>=2 && p<=5){
n++;
}
recc(n, a+1, b);
}
}
int partc(int a, int b){
int n = recc(0, a, b);
cout<<endl<< "part c = " << recc(0, a, b) << endl;
return n;
}
int main(){
int n=partc(2,9);
cout << n << endl;
return 0;
}
Not all control paths in your function return a value, so you were getting undefined behaviour when using the return value.
Now, this wasn't helped by the fact that the function itself is needlessly complicated. Let's rewrite it to use common practice for recursion:
int recc(int a, int b)
{
if (a > b) return 0;
int p = (a*a*a)%10;
int n = (p>=2 && p<=5) ? 1 : 0;
return n + recc(a+1, b);
}
Now your function is simpler. The recursion termination condition is right at the top. The function then decides whether a will contribute 1 or 0 to the count. And finally you return that value plus the count for a smaller range.
Notice how return n + recc(a+1, b); has broken the problem into a simple local solution combined with the recursive result of a reduced scope.
The invocation becomes simpler too, because you no longer have to pass in a redundant argument:
int partc(int a, int b)
{
int n = recc(a, b);
cout << endl << "part c = " << n << endl;
return n;
}
I need to make a program that calculates the power of a given number using a recursive function. I wrote this I can't get it to work, once I get to the function itself it breaks. Any help? Thanks.
#include"stdafx.h"
#include<stdio.h>
#include<iostream>
using namespace std;
float power(float a, unsigned int b);
int main()
{
float a = 0;
unsigned int b = 0;
cout << "Insert base - ";
cin >> a;
cout << "Insert index - ";
cin >> b;
float result;
result = power(a, b);
cout << result;
return 0;
}
float power(float a, unsigned int b)
{
if (b <= 0)
{
return a;
}
return (a*power(a, b--));
}
Instead of b-- you need b-1 (or --b)
b-- reduces b by one, which has no effect because that instance of b is never used again. It passes the unreduced copy of b recursively.
Also, when b is zero, the result should be 1 rather than a
if ( b <= 0) return 1;
return a * power(a, --b);
But this question was asked so many times....
Recursion function to find power of number
Whenever we think about recursion, the first thing that comes to mind should be what the stopping criterion is. Next thing to consider is that we cannot have recursion without the use of a stack. Having said this, let us see at how we are able to implement this power function.
Stopping criteria
X ^ 0 = 1
Unwinding the stack
The base number may be raised to a positive or negative real number. Let us restrict our problem to just integers.
If A is the base and B the power, as a first step, take the absolute
value of B.
Secondly, store A in the stack and decrement B. Repeat
until B = 0 (stopping criterion). Store the result in the stack.
Thirdly, multiply all the A's stored by unwinding the stack.
Now the code
float power(float a, int b)
{
int bx = -b ? b < 0 : b;
if (bx == 0)
{
a = 1;
return a;
}
return 1/(a*power(a, --bx)) ? b < 0 : (a*power(a, --bx));
}
#include <iostream>
using namespace std;
double calc(int a, int b);
int main()
{
int n1, n2;
cout << "Enter a number for a: ";
cin >> n1;
cout << "Enter a number for b: ";
cin >> n2;
cout << calc(n1, n2) << endl;
system("PAUSE");
return 0;
}
double calc(int a, int b)
{
double s;
s = (a) / ((sqrt(a / b)));
return s;
}
This program is meant to check whether the two integers are greater than zero. If it is it will calcualte the formula. Otherwise if one of the integers is zero or less than zero it will not return anything and exit the program.
My question here is that no matter what I input for a and b, i keep getting 1.#INF as the output and I have no idea why. I've checked the formula in a seperate program and it worked fine.
Any ideas?
Here, you are operating with int numbers:
s = (a) / ((sqrt(a / b)));
If a is less then b, then a/b (both are integers, remember, so the fractional part of the result will simply be lost) will be equal to 0, which leads to division by 0. You need to cast one of the numbers to double:
s = (a) / ((sqrt(static_cast<double>(a) / b)));
sqrt takes and returns a double. When you call it with integer arguments it will be converted in a double, and will thus get the value of infinity.
change your function signature to:
double calc(double a, double b);
and declare n1 and n2 as double.
You say that the function will exit the program when one of the integers are 0 or less, but where?
Try to check them like this:
Additionally, you should have a check whether a is greater than b
double calc(int a, int b)
{
double s;
if(a <= 0) exit(-1);
if(b <= 0) exit(-1);
if(a < b) exit(-1);
s = (a) / ((sqrt(a / b)));
return s;
}
You are having problems with infinity. For it use isinf. Here is some sample usage:
#include <stdio.h> /* printf */
#include <math.h> /* isinf, sqrt */
int main()
{
printf ("isinf(-1.0/0.0) : %d\n",isinf(-1.0/0.0));
printf ("isinf(sqrt(-1.0)): %d\n",isinf(sqrt(-1.0)));
return 0;
}
output:
isinf(-1.0/0.0) : 1 isinf(sqrt(-1.0): 0
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; }