C++ for loop variable increment by another variable - c++

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.

Related

use C++ to create a calculator

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;
}

How do I keep asking the user a question over and over again until they enter the correct field of value?

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;
}

Stumped with a transient population program in c++

this is my first time posting on here. Whenever I've gotten stuck on a programming problem, I've typically been able to find enough information to get me unstuck. I'm afraid that the issue I'm having though, I can't quite find an answer to. It's something I'd need someone to look at to tell me what I may be doing wrong in my code.
I have the program running successfully, and it DOES work. The issue however, is that my produced output is off by a few numbers when compared to the expected output on My Programming Lab. I'm really not sure of what to do to produce the correct output. Allow me to post both my source code, and a screenshot MPL's results screen.
SOURCE CODE:
#include <iostream>
using namespace std;
int populationCalculator(int, double, double, int, int);
int main()
{
int startingPopulation, newArrivals, peopleWhoLeft, years,
newPopulation, finalPopulation;
double deathRate, birthRate;
cout << "This program calculates population change.\n";
cout << "Enter the starting population size: ";
cin >> startingPopulation;
while (startingPopulation < 2)
{
cout << "\nThe starting population may not be less than two. Please
re - enter: ";
cin >> startingPopulation;
}
cout << "Enter the annual birth rate (as % of current population): ";
cin >> birthRate;
while (birthRate < 0)
{
cout << "\nBirth rate percent cannot be negative. Please re -
enter:";
cin >> birthRate;
}
birthRate = birthRate / 100;
cout << "Enter the annual death rate (as % of current population): ";
cin >> deathRate;
while (deathRate < 0)
{
cout << "\nDeath rate percent cannot be negative. Please re -
enter: ";
cin >> deathRate;
}
deathRate = deathRate / 100;
cout << "How many individuals move into the area each year? ";
cin >> newArrivals;
while (newArrivals < 0)
{
cout << "\nArrivals cannot be negative. Please re - enter: ";
cin >> newArrivals;
}
cout << "How many individuals leave the area each year? ";
cin >> peopleWhoLeft;
while (peopleWhoLeft < 0)
{
cout << "\nDepartures cannot be negative. Please re - enter: ";
cin >> peopleWhoLeft;
}
cout << "For how many years do you wish to view population changes? ";
cin >> years;
while (years < 1)
{
cout << "\nYears must be one or more. Please re - enter: ";
cin >> years;
}
newPopulation = populationCalculator(startingPopulation, deathRate,
birthRate, newArrivals, peopleWhoLeft);
cout << "\nStarting population: " << startingPopulation << endl;
for (int loopCount = 1; loopCount <= years; loopCount++)
{
newPopulation = populationCalculator(newPopulation, deathRate,
birthRate, newArrivals, peopleWhoLeft);
cout << "Population at the end of year " << loopCount << " is: " <<
newPopulation << endl;
}
system("pause");
return 0;
}
int populationCalculator(int Population, double deathRate, double birthRate,
int newArrivals, int peopleWhoLeft)
{
int newPopulationCount;
newPopulationCount = Population + (Population * birthRate) - (Population
* deathRate) + newArrivals - peopleWhoLeft;
return newPopulationCount;
}
MPL RESULTS:
http://imgur.com/a/mRmpc
I really will appreciate if anyone can help me figure out why my produced output is off by a few numbers.
Step through your code. You're returning an int where you have double and int multiplication. Make sure that you aren't truncating values that might need to be rounded up or down.
Does birth happen before or after death? Should it occur in steps, or all at once like you have shown?
try casting to a double in your operations that involve doubles and integers. For example
birthRate = (double)(birthRate / 100);
deathRate = (double)(deathRate / 100);
Sometimes programming languages will cast a double to an integer, which causes your numbers to be off.
Perhaps the number were rounded off?
I assume this is the case because I noticed you declared some variables in double but the end result is integer. Try to change the data type of the method
populationCalculator(), newPopulation and of course the returning values of the method populationCalculator() from int to double.

Function not working correctly?

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 --;

I'm having trouble writing a console application to create a simple program to solve a math equation for superannuation

Could some one help me with this?
I've racked my head over an hour and I can't get it to work.
This is in C++ and I've been learning for a little bit but I'm still new...
int main()
{
double rate, amount,time, S;
cout << "Insert the time of the super: ";
cin >> time;
cout << "Insert the rate (as a decimal, eg 1% AKA 101% = 1.01): ";
cin >> rate;
cout << "Insert the amount $: ";
cin >> amount;
S =("amount * (rate ^ time - 1)", pow(rate,time));
cin >> S;
cout << "The total amount is: " << "S /(rate - 1)" << endl;
system("PAUSE");
return 0;
}
i dont get a compile error but i can never get an answer from it
You "never get a result" because you're setting S to the result of pow with comma operator weirdness then assigning to it again with the line
cin >> S;
which is waiting for you to input another number.
You have two main problems. Here is the updated code with comments on the altered parts:
int main()
{
double rate, amount,time, S;
cout << "Insert the time of the super: ";
cin >> time;
cout << "Insert the rate (as a decimal, eg 1% AKA 101% = 1.01): ";
cin >> rate;
cout << "Insert the amount $: ";
cin >> amount;
S = amount * pow(rate, time - 1); // take away the quotes and don't make pow seperate
cout << "The total amount is: " << (S /(rate - 1)) << endl; // do the calculation and output it
system("PAUSE");
return 0;
}
Remember that things inside quotes "like this" are string literals, so "4 * 4" is a string but 4 * 4 (see the absence of quotes) does multiplication which yields the number 16.
I don't think you should assign values to S the way you are doing it. S is declared as double and you are assinging a string to it initially. And when you output the result you are also enclosing the calculation in quotes. You should simply cout << S / (rate-1); // without quotes or cout will simply output the string