I am trying to create an exponent function and it does not seem to work as expected. Sorry if I don't understand some basic things, I'm just learning bits and pieces off the internet.
float x;
float y;
float z;
int h;
int j;
float exponent (float a, float b)
{
float r;
while(b > 1)
{
r = a * a;
b = b - 1;
}
return (r);
}
^Snippet of the function with variables.
cout << "EXPONENT MODE\n\n";
cout << "Please enter a number: ";
cin >> x; system("CLS");
cout << "Please enter another number as the exponent for the first: ";
cin >> y;
z = exponent(x, y);
cout << "Calculating the answer, please wait";
Sleep(1000);
cout << ".";
Sleep(1000);
cout << ".";
Sleep(1000);
cout << ".";
Sleep(1000);
cout << "\n\nYour answer is : ";
cout << r;
Sleep(5000);
system("CLS");
cout << "Would you like to calculate another set of numbers? (yes = 1, no = 2) : ";
cin >> h;
system("CLS");
^Part I want to execute on the console.(Just code)
Basically, I want the user to input 2 numbers, the first(x) being the base number, the second(y) being the exponent. The program should input x as a and y as b and run the function. What happened: Input 1: 5, Input 2: 3, Expected: 125, Received: 25. I'm thinking about changing the while to (b > 0). If you guys could help that would be great!.
(Also don't judge me on the system("CLS") in the code)
It's fairly simple, you're printing the wrong variable.
cout << "\n\nYour answer is : ";
cout << r;
r is a local member variable of exponent. In the scope of main, the result of exponent was actually stored in a variable called z
z = exponent(x, y);
The fix is just to change your answer printing code to
cout << "\n\nYour answer is : ";
cout << z;
For your own benefit, you might want to try giving your variables more meaningful names and only declaring them in scopes where they are actually needed. I don't see you using r elsewhere in main, did you make it global in an attempt to try and make the r in exponent accessible there too?
I dont under stand what #kfsone is talking about.
but in the loop r is set as a*a everytime, isn't this why you are getting the square instead of exponent ? I think what you really want to do is this:
r=1
while( ...
r *= a;// note to accumulate result on r
b --;
Related
I'm trying to compute the formula "V / I = R" in my program by asking the user to input values for V and I. Unfortunately my program does not compile and I'm not sure why.
#include <iostream>
using namespace std;
int main()
{
int V, I, R;
cout << "Please enter the voltage: " << endl;
cin >> V;
cout << "Please enter the curruent: " << endl;
cin >> I;
V / I = R;
cin >> R;
cout << "The value of the resistor is: " << R << endl;
system("PAUSE");
}
C++ is not a system to solve linear equation, you must tell it what to do.
You need to replace:
V / I = R;
cin >> R;
with
R = V / I;
The knowledge you used, to flip the equation around, stays with you. The compiler needs instructions. Also note the = is not the symbol for equality. It is the symbol for assignment. It evaluates the right-hand side and assigns it to the variable on the left-hand side. Some other language write it := to make this clearer.
You should also use float instead of int if you want to be able to get fractional answers, like 0.5.
I want to use C++ to make a calculator, so that I can enter an expression and calculate the result.
For example,
input
(5.2+4)*ln3.4+sin3
output
11.39985
The problem is that I don't know how to separate the number and the operator from the string. For the length of the operands and numbers are different.
Is there any good way?
That's actually a much harder problem than it seems at first, and I say that from experience.
If you want an example of how to do it completely from scratch, here is a question where I posted an example I was working on. It is certainly not complete, but links to a great Java article (actually, probably the best article) on Pratt parses, which in my opinion is the best way to parse expressions. My question was on my attempt to port the Java code found there to C++. You can see a problem I ran into there.
You will also need to know some theory on lexers, and learn how to create tokens, which I don't ask about there.
The point is, you have a lot of research ahead of you, if you want to start from scratch, or even if you want to just know the theory of what's going on, but I certainly encourage you to try it if you don't have a deadline for it.
Use a library such as exprtk.
I'm going to assume that you're a total noob which leads me to advise you to always Google for a library that solves your problem.
I programmed the calculator using function ,loops, switch case.
it can also be programmed with using if else statement but then it will be a simple one. I had made it like a real calculator it can take unlimited argument, while the other takes only 2 numbers as argument.
#include <iostream>
#include <conio.h>
using namespace std;
int add()
{
int total, a, sum = 0;
cout << "how much number you want to calculate :";
cin >> total;
for (int i = 1; i <= total; i++)
{
cout << "enter number " << i << "for +" << endl;
cin >> a;
sum = sum + a;
}
cout << "total addition is:" << sum;
return 0;
}
int subtract()
{
int sub = 0, a, b[20], total;
cout << "how much number you want to calculate :";
cin >> total;
cout << "enter number 1 for - : \n";
cin >> a;
a = -a;
for (int i = 1; i < total; i++)
{
cout << "enter number " << i << "for - :" << endl;
cin >> b[i];
sub = sub - a - b[i];
a = 0;
}
cout << "HENCE THE SUBTRACT IS :" << sub;
}
int divide()
{
float h;
float a;
float b;
cout << "enter number 1 : ";
cin >> a;
cout << "enter number 2 : ";
cin >> b;
h = a / b;
cout << "division is :" << h;
}
int multiply()
{
int a[20];
int total, multi = 1;
cout << "how much number you want to multiply\n";
cin >> total;
for (int i = 0; i < total; i++)
{
cout << "enter number to multiply\n";
cin >> a[i];
multi = multi * a[i];
}
cout << "multiplicaion is : " << multi;
}
int main()
{
int num1[20], num2[20];
char sign;
cout << "chouse a sign"
"\npress this for executing the action +"
"\npress this for executing the action -"
"\npress this for executing the action X"
"\npress this for executing the action /\n";
cin >> sign;
switch (sign)
{
case '+':
add();
break;
case '-':
subtract();
break;
case '*':
multiply();
break;
case '/':
divide();
break;
default:
cout << "chouse something";
break;
}
return 0;
}
I am a rookie coder here and I can't seem to figure out what to add to my code here to get it right. It is supposed to ask the user again if they do not answer the question "Do you want to make another calculation Y or N?" correctly. I want it to repetitively ask the user to enter y or n if they enter something else. I feel like it is obvious I am just missing it. This is for school, to be clear.
I've tried nesting a do while loop and an if statement but only to get run time errors
#include <iostream>
using namespace std;
int main() {
int base, exponent;
long int result = 1;
char choice;
int i;
do
{
cout << "This program raises a number to a specific power." << endl;
cout << "\nEnter a base integer greater than 1: ";
cin >> base;
cout << "\nEnter an exponent integer to raise that number to: ";
cin >> exponent;
for (i = 1; i <= exponent; i++)
{
result = result * base;
}
cout << "\n" << base << " to the power of " << exponent << " = " << result << endl;
result = 1;
// ***** HERE IS WHERE I NEED HELP, WHAT TO
// DO IF THEY DONT ENTER Y OR N.....
cout << "\nWould you like to make another calculation? Y or N: ";
cin >> choice;
cout << endl;
}
while (choice == 'y' || choice == 'Y');
cout << "Good bye, then. Have a good day.\n" << endl;
return 0;
}
When I tried adding a nested do while loop, and entered a character answer other than y or n, it would go to a part of the program it should not have.
*this is my first question so I hope I've done this correctly
You can use another do-while loop to wrap the input section.
do
{
cout << "This program raises a number to a specific power." << endl;
cout << "\nEnter a base integer greater than 1: ";
cin >> base;
cout << "\nEnter an exponent integer to raise that number to: ";
cin >> exponent;
for (i = 1; i <= exponent; i++)
{
result = result * base;
}
cout << "\n" << base << " to the power of " << exponent << " = " << result << endl;
result = 1;
do
{
cout << "\nWould you like to make another calculation? Y or N: ";
cin >> choice;
cout << endl;
} while (choice != 'y' && choice != 'Y' && choice != 'n' && choice != 'N');
}
while (choice == 'y' || choice == 'Y');
Learn to think organically here. Let me do a procedural approach.
We begin by bringing your formulations into a more technical form, until it is syntactically and semantically working. Let's start by transforming it into this:
void process_things()
{
...
while(still_require_answer)
{
ask_for_answer();
}
...
}
This is very close to how you formulate it verbally, yes? Now, let's flesh it out.
string ask_for_answer(bool& still_require_answer);
void process_things()
{
...
string answer = "";
bool still_require_answer = true;
while(still_require_answer)
{
answer = ask_for_answer(still_require_answer);
}
...
}
// hope you understand the concept of a reference here,
// that is what the ampersand (&) does, if not, ask
string ask_for_answer(bool& still_require_answer)
{
string answer = ""; // always initialize
cout << "State answer: ";
cin >> answer;
cout << endl;
if(answer == "Y" or ...)
{
still_require_answer = false;
}
return answer;
}
Hope this helps you. In the long run, you might want to go OOP and use classes here. The code here is a little bit verbose, but orderly.
Note that I have put the routine in a new function process_things. Anything that is more than a few lines which you can name you should think about making a function (or a class method). Your main should be quite small. Cutting things down into smaller units helps you keeping thisng orderly and makes the design of each single unit easy (divide-and-conquer) and allows you to quicker locate problems as you can test every function separately (later, this leads to automated unit tests).
One could also take the while and put it into it's own function string ask_until_valid_answer();, and if we do that, dissolve ask_for_answer and put it's content there. What I want to focus on is to have it organically, that is use self-descriptive names which explain the program while reading it, and to cut the program into understandable units. Here would be this other layout:
string ask_until_valid_answer();
void process_things()
{
...
string answer = ask_until_valid_answer();
...
}
string ask_until_valid_answer()
{
string answer = "";
bool still_require_answer = true;
while(still_require_answer)
{
cout << "State answer: ";
cin >> answer;
cout << endl;
if(answer == "Y" or ...)
{
still_require_answer = false;
}
}
return answer;
}
I have been working on a simple grade calculator, I am having trouble with the "labs" option spitting back a bad result, I am looking for a decimal percent, but I keep getting a very very large exponential number.
The specific part I am having trouble with is the calclabavg() function-- the for loop to be exact.
I am not asking for an exact solution, I just want to be pointed in the right direction so that I can solve the problem on my own.
Thanks so much in advance :)
float calclabavg(){//funciton that calculates user lab averages
float x, vary, pointspos, sumpointspos, sumearned;
cout << "How many labs in labs?" << endl;
cin >> x;
float totalpoints = 0;
cout << "Do the points vary per lab? (Press 1 for yes, 0 for no)" << endl;
cin >> vary;
if (vary == 0){
cout << "How many points were possible on each lab?" << endl;
cin >> pointspos;
sumpointspos = x * pointspos;
}
for (int i = 0; i < x; i++){
float temp;
cout << "What was your score on lab " << i + 1 << endl;
cin >> temp;
sumearned += temp;
if (vary == 1){
cout << "How mant points possible on lab " << i + 1 << endl;
float pointsposvary;
cin >> pointsposvary;
sumpointspos += pointsposvary;
}
//pointspos = pointspos + temp;
}
return sumearned / sumpointspos;
}
It seems as if you do not initialize sumearned.
Statement sumearned = 0.0; at the beginning of calclabavg should bring you at least a step further. BTW: initialising also the other variables is good practice and makes code more stable.
I created this little software which can calculate the surface and the perimeter of the rectangle and the square. However, it is getting very hard for me to run this program. What I mean is that when I try to run it, the software works fine for the "square" part, but it closes immediately when I go to the "rectangle" part. Can anyone help me? Thank you very much!
#include<iostream>
using namespace std;
int main ()
{
double a, b, c, answer, x, y, z;
cout << "Square (1) or rectangle (2) ";
cin >> x ;
if (x==1)
{
cout << "Square side: ";
cin >> a;
cout << " Type (2) if you would like to calculate the Perimeter or (1) if you would like to calculate the surface?";
cin >> y;
if (y == 1)
{
cout<<"The surface of the square is: ";
answer = ( a * a );
cout << answer << endl;
}
else if (y == 2)
{
cout << "The perimeter of the square is: ";
answer = (4*a);
cout << answer << endl;
}
else if (x==2)
{
cout << "The first side of the rectangle is: ";
cin >> c;
cout << "The second side of the rectangle is: ";
cin >> b;
cout << " Type (2) if you would like to calculate the Perimeter or (1) if you would like to calculate the surface? ";
cin >> z;
if (z == 1)
{
cout << "The surface of the rectangle is: ";
answer = (c*b);
cout << answer<<endl;
}
else if (z == 2)
{
cout << "The perimeter of the rectangle is: ";
answer = 2 * (c + b);
cout << answer << endl;
}
}
system("pause");
return 0;
}
You are missing a closing brace before else if (x==2)
It is a good idea to make the indentation match the braces - easier to spot this type of bug
`
You have a curly bracket(}) missplaced. You need to close it before else if (x==2) because otherwise the else if applies to else if (y==2) instead to x == 1. Improve your code style as pointed in IntermediateHacker's comment and you should be able to avoid such errors.
I have spend a lot of time formatting your code. Still there are obvious problems with it. The curly braces just do not match. You don't even have opening brace for the main method. You also do not have curly brace before else if (x==2). If you have paid some more effort formatting your code it would have been easier for you to detect your problem.