I am making a c++ program which functions as a calculator. Everything works except for the division function, which adds the doubles for some reason. Anyone have a fix?
I have tried explicitly casting to a double and banging my head on my desk. Here are a few snippets of my code.
#include "pch.h"
#include <iostream>
using namespace std;
void divide()
{
//first number
cout << "What is the numerator?";
double firstNum = 0;
cin >> firstNum;
//second number
cout << "What is the denominator?";
double secNum = 0;
cin >> secNum;
//multiplying
double answer = firstNum/(double)secNum;
cout << "Your answer is " << answer << ".";
}
int main()
{
//asks for what operation user would like to use
cout << "Do you want to add, subtract, divide, or multiply? Type [1] for add, [2] for subtract, [3] for divide, and [4] for multiply(minus the brackets).";
double opquery = 0;
cin >> opquery;
// if division
if (opquery == 3)
{
divide();
return 0;
}
}
I would have expected something like 4/4 to equal 1, but it just returns addition
UPDATE: FULL CODE CAN BE FOUND AT https://github.com/hoverdoge/cppcalculatorerror/blob/master/code
Actually, the code you share here is ok and the result of 4/4=1.
But the code you share in the github has something different. Remove
the ;after if (opquery == 1); The program can work normally.
Changes from:
if (opquery == 1);
{
add();
return 0;
}
To:
if (opquery == 1)
{
add();
return 0;
}
Note: When you add the extra ;after if(xxx), whatever the value of opquery is, the main method will execute steps below:
cout << "xxx...";
int opquery = 0;
cin >> opquery;
add();
return 0;
That's why this issue occurs.
Related
I made here a program to do 3x+1 math problem. So I am asking, if I could write in a c++ code something like x/2;, or x*3+1. These stuff what i put here are with mistakes. Then, is it possible in c++ to do that? If yes, how?
Here's the code:
#include <iostream>
using namespace std;
int main() {
cout << "Write an integer.\n"; int x; cin >> x;
// I made here a program to do 3x+1 math problem.
while (x==1) {
if ((x%2)==0) {
x/2; cout << x << ", ";
} else if ((x%2)==1) {
x*3+1; cout << x << ", ";
}
}
return 0;
}
The output there was:
/tmp/GjudkYOaE4.o
Write an integer.
9
But I was waiting it to write the number 28, 14, and more, but it did nothing.
I can see that you are new to coding, I would suggest you to please read a good amount of information about if-elseif-else and while loop that you are using
I can show you a few corrections here
#include <iostream>
using namespace std;
int main() {
cout << "Write an integer.\n";
int x; cin >> x;
// I made here a program to do 3x+1 math problem.
while (x!=1) { // x!=1 could be one of the terminating condition so when your x becomes 1, the loop would end. But of course the terminating condition depends on what you are trying to achieve
if (x % 2 == 0) {
x = x/2; //you need to assign the value back to x
cout << x << ", ";
} else { // you dont need else-if here because there could only be 2 possibilities for %2 operaion here
x = x*3+1;
cout << x << ", ";
}
}
return 0;
}
Give value to the same variable with assignment operator ('='):
x = x*3+1;
or
x = x/2;
I want to create a program that when a user inputs something that I didn't define, the program prompts him again.
I did it with if statements but it only loops for 1 time and doesn't do it again. I tried loops but whenever the input is false it just breaks the condition and refuses all inputs alike. In c++.
Any help is much appreciated.
#include <iostream>
#include <string>
using namespace std;
void xD(){string x;
do{cout << "Retry\n";
cin >> x;}while(true);}
//declaring a function to make the shop
void shop(){
string x;
float coins = 500;
float bow_cost = 200;
cout << "welcome to the shop\n";
cout << "Bow(bow)costs 150 coins.\n";
cin >> x;
// if u chose bow you get this and get to choose again
if (x == "bow"){
cout << "you bought the bow.\n you now have " <<coins - bow_cost << " coins." << endl; cin >> x;}
/*now the problem that whenever I excute the code and type something other than bow it gives me the cin only once more and then fails even if I type bow in the 2nd attempt*/
//in my desperate 5k attempt, I tried creating a function for it.. no use.
//i want it o keep prompting me for input till i type "bow" and the other block excutes. but it never happens.
else{xD();}
}
int main(){
string name;
string i;
cout << "if you wish to visit the shop type \"shop\"\n";
cin >> i;
if(i == "shop"){shop();}
else{cin >> i;}
return 0;
}
The problem lies on the condition in this loop block
void xD(){
string x;
do{
cout << "Retry\n";
cin >> x;
}while(true);
}
The while(true) condition makes it loops forever regardless of the input. To fix this, you can change the condition:
void xD(){
string x;
do{
cout << "Retry\n";
cin >> x;
}while(x!="bow");
cout << "you bought the bow. and some other messages"<<endl;
}
That should work. However, it is still too complicated for me. This can be simplified into the snippet below:
void shop(){
string x;
float coins = 500;
float bow_cost = 200;
cout << "welcome to the shop\n";
cout << "Bow(bow)costs 150 coins.\n";
cin >> x;
while (x!="bow"){
cout << "Retry\n";
cin>>x;
}
cout << "you bought the bow.\n you now have " <<coins - bow_cost << " coins." << endl; cin >> x;
}
Instead of doing this approach (which is checking the condition only once):
if (x == "bow"){
cout << "you bought the bow.\n you now have " <<coins - bow_cost << "
coins." << endl; cin >> x;
} else{
xD();
}
which is actually a RECURSIVE invocation to the method xD()
you should do a do-while loop,
example:
while (x.compare("bow") != 0)
{
cout << "sorry, wrong input, try again...";
cin >> x;
}
note the use of the compare method instead of the == operator
here more about it in the documentation
You can use return value of cin >> [your input object] here to check status or istream's method fail(). As soon as input stream fails to parse whole or part of streams it fails and stay in state of failure until you clear it. Unparsed input is preserved (so you can try to parse it differently?)m so if you try to >> again to object of same type, you'll get same failure. To ignore N chars of imput, there is method
istream::ignore(streamsize amount, int delim = EOF)
Example:
int getInt()
{
while (1) // Loop until user enters a valid input
{
std::cout << "Enter an int value: ";
long long x; // if we'll use char, cin would assume it is character
// other integral types are fine
std::cin >> x;
// if (! (std::cin >> x))
if (std::cin.fail()) // has a previous extraction failed?
{
// yep, so let's handle the failure, or next >> will try parse same input
std::cout << "Invalid input from user.\n";
std::cin.clear(); // put us back in 'normal' operation mode
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n'); // and remove the bad input
}
// Thechnically you may do only the above part, but then you can't distingusih invalid format from out of range
else if(( x > std::numeric_limits<int>::max()) ||
( x < std::numeric_limits<int>::min()))
{
std::cout << "Invalid value.\n";
}
else // nope, so return our good x
return x;
}
}
For strings parsing is almost always successful but you'll need some mechanism of comparison of string you have and one that is allowed. Try look for use of std::find() and some container that would contain allowed options, e.g. in form of pair<int,string>, and use int index in switch() statement (or use find_if and switch() within the function you give to it).
Consider that if() statement is a one_direction road, it checks the condition and if the condition was satisfied it goes to its bracket and do blah blah blah , if there is any problem with condition compiler passes ifand jump to compile other codes.
Every time that you begin to compile the codes it begins from int main() function. You did the wrong thing in the if and else statements again
Here is the correct code .I did the necessary changes.
#include "stdafx.h"
#include <iostream>
#include <string>
using std::string;
using std::cin;
using std::cout;
#define coins 500 ;
#define bow_cost 200 ;
int shop(string x)
{
//There is no need to allocate extra memory for 500 and 200 while they are constant.``
cout << "welcome to the shop\n";
cout << "Bow(bow)costs 150 coins.\n";
do
{
cout << "Input another :\n";
cin >> x;
if (x == "bow")
{
return (coins - bow_cost); //return to function as integer
}
} while (true);
}
int main()
{
string name, i;
cout << "if you wish to visit the shop type \"shop\"\n";
cin >> i;
if (i == "shop")
{
cout << "Input :\n";
cin >> name;
cout << shop(name) << "you bought the bow.\n you now have " << " coins." << "\n";
}
//argument passed to shop funnction parameters.
system("pause");
return 0;
}
I'm currently learning about functions in C++ and am currently working on a homework assignment with functions being the main thing.
Currently, I'm trying to make a grade calculator with every operation of the process being split into a function of its own.
Here's the code:
#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
using namespace std;
void getHWGrades(int homeworks[], int size)
{
cout << "\nEnter the grades, out of 100 points, for the 9 homeworks you completed." << endl;
cout << "Note that Homework 10 is given to you for free, but is the same grade \nas homework 9.\n" << endl;
for (int i = 0; i < 9; i++)
{
cout << "Homework " << i + 1 << ": ";
cin >> homeworks[i];
while (homeworks[i] > 100 || homeworks[i] < 0)
{
cout << "Invalid grade, input homework grade again: ";
cin >> homeworks[i];
}
}
homeworks[9] = homeworks[8];
cout << "Homework 10: " << homeworks[9];
}
double quizAverage()
{
double quizPts;
cout << "Input your in class quiz average: ";
cin >> quizPts;
return quizPts;
}
double labAverage()
{
double labPts;
cout << "Input your lab average: ";
cin >> labPts;
return labPts;
}
double teamProject()
{
double teamPts;
cout << "Input your team project grade: ";
cin >> teamPts;
return teamPts;
}
int exam1()
{
int exam1Pts;
cout << "Input your exam1 grade: ";
cin >> exam1Pts;
return exam1Pts;
}
int exam2()
{
int exam2Pts;
cout << "Input your exam2 grade: ";
cin >> exam2Pts;
return exam2Pts;
}
double hwAverage(int homeworks[], int size)
{
double total = 0;
double homeworkAverage = 0;
for (int i = 0; i < size; i++)
{
total = total + homeworks[i];
}
homeworkAverage = (total*1.0) / 10;
return homeworkAverage;
}
double currentPoints(double& quizPts, double& labPts, double& teamPts, double& homeworkAverage, int& exam1Pts, int& exam2Pts)
{
double totalPts = ((quizPts / 100.0) * 10) + ((labPts / 100.0) * 10) + ((teamPts / 100.0) * 15) + ((homeworkAverage / 100.0) * 20) + ((exam1Pts / 100.0) * 10) + ((exam2Pts / 100.0) * 15);
cout << "\nYour current points (out of the 80 total available), stand at: " << totalPts;
return totalPts;
}
double currentAverage(double& totalPts)
{
double availableAverage = totalPts*(100.0 / 80);
cout << "\nYour current average is: " << availableAverage;
return availableAverage;
}
int main()
{
// keep the console from closing in visual studio
char charer;
double totalPts;
double quizPts, labPts, teamPts, homeworkAverage;
int exam1Pts, exam2Pts;
const int ARRAY_SIZE = 10;
int hwArray[ARRAY_SIZE];
getHWGrades(hwArray, ARRAY_SIZE);
quizAverage();
labAverage();
teamProject();
exam1();
exam2();
currentPoints(quizPts, labPts, teamPts, homeworkAverage, exam1Pts, exam2Pts);
currentAverage(totalPts);
cin >> charer;
}
My issue, which I believe lies in the functions currentPoints and currentAverage, is that when I run this totalPts outputs as -5.09078e+61 and as a follow up result with the currentAverage function, availableAverage outputs as -1.157e+62.
I'm sure that the issue has to do with how I'm passing the values from function to function (which I doubt I'm doing correctly).
How would I go about fixing this issue?
Thank you in advance.
You need to store the return value from currentPoints() function, like this.
totalPts = currentPoints(quizPts, labPts, teamPts, homeworkAverage, exam1Pts, exam2Pts);
currentAverage(totalPts);
Reason is, you declared "totalPts" as local variable in currentPoints().
"Local variables has function scope only, it is undefined to main function".
Do this for all other
functions(quizAverage,labAverage,teamProject,exam1,exam2, hwAverage,currentAverage)
I hope, this will solve the issue !!!
The problem is not about functions, it's about variables.
Let's take quizPts for instance:
In the main method, you declare this variable, but then you don't do anything with it before sending it to currentPoints. Therefore it has an undefined value when you do so (undefined often looks like random in C).
The other variable quizPts you use in quizAverage have the same name but is not the same for the compiler.
Try in your main:
quizPts = quizAverage();
You asked
How would I go about fixing this issue?
And the answer is "Use the debugging tool with "watches" window open in your favorite IDE".
It's always very difficult to find an error simply by re-reading the code, but in the debugger you can see all the values of your variables at each moment of time. Specifically, in this example, you would realize that your variables have garbage values from the very beginning (are not initialized), and this value never changes.
Using this approach you could find the reason yourself in time less than necessary to write this SO question. I hope this will help you to save your time in future.
The problem is you use the variables such as quizPts and labPts without storing any value in them. In your case, you have to store the return value of the function to the corresponding variable before using it. For example, do the same as the following statement:
quizPts = quizAverage();
I have those two pieces of code as my home assignment. The code looks all fine to me, but it won't print out what I want, no matter what. In fact, the console output remains completely empty.
The first program is supposed to print out all numbers that fulfil the ladna() function requirements and are between 1 and a:
#include <iostream>
using namespace std;
int a;
int i = 1;
bool ladna(int a)
{
if((((a>>4)*5+a*2)%3)==1)
return true;
else
return false;
}
int main()
{
cerr << "Podaj liczbe: " << endl;
cin >> a;
while (i <= a){
if (ladna(a)){
cout << i << " ";
}
i++;
}
}
the ladna() function is premade and I have to use it as is.
I tried changing while into do...while and for, didn't help. Doesn;t work with cerr either.
The second code has to print out all the natural divisors of number a.
#include <iostream>
using namespace std;
int main()
{
int a;
cerr << "Podaj liczbe" << endl;
cin >> a;
for (int i = 0; i >= a; i++){
if (a % i == 0){
cout << i << endl;
}
}
return 0;
}
Doesn't work either.
To me it looks like both pieces of code have the same issue, because they are written in the same way, based on the same principle, and the error is the same. Hence my assumption, that the cause is the same as well.
Unfortunately, for the love of me, I simply can't see what said error is...
For the first code:
I think you should call ladna function with i, like ladna(i)
For the second code:
In for it should be i<=a
'%' is the modulo operator, during the execution of (a%i) you divide a with i and take the remainder, since i start with zero you will get "Floating point exception (core dumped)" due to division by zero. So, for should start with 1. This should work:
for (int i = 1; i <= a; i++){
if (a%i == 0){
cout << i << endl;
}
}
I have a basic issue that hopefully someone here can help me with. I'm quite confident it's a small, forgetful type of issue, missing return or something similar.
///////////////////////////
//My Basic Calculator App
//Written by l8nit3tr0ubl3
//of NottaDev inc.
///////////////////////////
#include <iostream>
void in() //Take input from user, all 3 variables.
{
int add(int, int); //Forward declarations
int minus(int, int);
int divide(int, int);
int multiply(int, int);//end declarations
std::cout << "My Basic Calculator\n";//take inputs
std::cout << "Please input your first number.\n";
int firstNumber;
std::cin >> firstNumber;
std::cout << "Choose math function.\n";
std::cout << "Eg. *-+/\n";
char operatorType;
std::cin >> operatorType;
std::cout << "Please input second number.\n";
int secondNumber;
std::cin >> secondNumber;//end inputs
if (operatorType == '+') //determine math function to use
add(firstNumber, secondNumber);
else if (operatorType == '-')
minus(firstNumber, secondNumber);
else if (operatorType == '/')
divide(firstNumber, secondNumber);
else if (operatorType == '*')
multiply(firstNumber, secondNumber);//end math function
}
int add(int firstNumber, int secondNumber) //Actual math is done
{
return firstNumber + secondNumber;
}
int minus(int firstNumber, int secondNumber)
{
return firstNumber - secondNumber;
}
int divide(int firstNumber, int secondNumber)
{
return firstNumber / secondNumber;
}
int multiply(int firstNumber, int secondNumber)
{
return firstNumber * secondNumber; //End math
}
int main()
{
in(); //Call input, which will call math function
return 0; //return '0' for no error.
}
Can somebody please tell me what ive forgotten to call or return??
I should have been more precise on my question and i apologize for not doing so. There are no errors produced, i was simply unable to echo my answer to console. However there is a perfect answer supplied below
Your add, multiply etc. functions return the result of the operation, but you're not doing anything with it.
You could for example print it:
std::cout << add(firstNumber, secondNumber) << std::endl;
Probably you want to output the result of your calculations.
So write
std::cout << add(firstNumber, secondNumber);
But even nicer it is, if you do the output only once. For this use a temprary variable, for example
result = add(firstNumber, secondNumber);
...
std::cout << "The result is " << result << std:endl;
Your add, multiply and minus functions are returning back to void in(), and you have no variable assigned to them when they are returned.