I have created a project that breaks a big number to its roots, it works very well, but it prints an extra * at the end of the last root.
#include <iostream>
using namespace std;
int multinum(int a, int b);
int primeOp(int a);
int main()
{
char ch;
do {
int a=0, b=0;
multinum(a,b);
cout << "\n\nDo you want to continue?(y/n)";
cin >> ch;
} while (ch=='y');
return 0;
}
int multinum(int num1, int num2)
{
cout<< "\nPlease enter the first number : ";
cin >> num1;
cout << "\nPlease enter the second number : ";
cin >> num2;
cout << num1 <<" = ";
primeOp(num1);
cout << endl;
cout << num2 <<" = ";
primeOp(num2);
return 0;
}
int primeOp(int a)
{
int i, x, power;
x=a;
if (a%2==0)
{
power=0 ;
while(a%2==0)
{
a/=2;
power++;
}
cout << 2 <<"^"<<power<< "*";
}
for (i=3; i<=x/2; i+=2)
{
power=0 ;
while(a%i==0)
{
a/=i;
power++;
}
if (power!=0)
cout << i <<"^"<< power << "*";
if (power!=0 && a%i== 0)
cout << "*";
}
if(a==x)
cout<< x << "^" << 1;
return 0;
}
I tried to print * in different ways but none of them had any effect, I also tried to stop printing by the use of the last "i" or "power" but it was useless.
What should I do, to stop the * bring printed when it's not needed?
Example: 24 = 2^3 * 3^1 * --- it should become: 24 = 2^3*3^1
To be able to print something only sometimes you need to print it under an if, and you need a condition that will control that print. A bool flag should do the trick. The other part of the trick is to print the asterisk before the next component, not after.
void PrintComponent(int root, int power, bool& printStar)
{
if (printStar)
cout << " * ";
cout << root << "^" << power;
printStar = true;
}
int primeOp(int a)
{
int i, x, power;
bool printStar = false;
x = a;
if (a % 2 == 0)
{
...
PrintComponent(2, power, printStar);
}
for (i = 3; i <= x / 2; i += 2)
{
...
if (power != 0)
PrintComponent(i, power, printStar);
}
if (a == x)
PrintComponent(x, 1, printStar);
return 0;
}
If finding the last print is not easy make the first print special.
Print the first power like this:
cout << 2 <<"^"<<power;
Then print all the rest via
cout << "*2^"<<power;
I dont understand your code fully, but to know it is the first print you can use a boolean flag.
You can suppres this issue by printing backspaces at the end of the result.
In primeOp add:
cout <<"\b \b";
Just above return statement
Related
I'm trying to make a simple user input. I tried to set it up so there would be four numbers entered by the user. It works for four inputs from user. It does not end after four separate numbers. Also managed to find out that I can trigger an endless repeating loop if one really long number is entered. Then I have to press cntrl+C to stop the code from running. This is in Microsoft Visual Studio if that is important.
#include <iostream>
using namespace std;
void GameBoy ()
{
cout<< "\nYou think you are this badass hacker so...." <<endl;
cout<< "Please enter the correct combination of numbers..." <<endl;
int a {};
int b {};
int c {};
int d {};
cin >> a >> b >> c >> d;
double sum = a + b + c + d;
int prod = a * b * c * d;
double average = sum / 4;
cout << average << endl;
if (sum != average && average == sum)
{
cout << "You're a goober!!" << endl;
}
else
{
cout << "You're still an goober :-P" << endl;
}
}
int main()
{
while (true)
{
GameBoy ();
}
return 0;
}
You can modify your function to return bool (true if all numbers are in the correct range, false if some number is out of range). Something like this:
#include <iostream>
using namespace std;
bool GameBoy() {
cout << "\nYou think you are this badass hacker so...." << endl;
cout << "Please enter the correct combination of numbers..." << endl;
int a{};
int b{};
int c{};
int d{};
cin >> a >> b >> c >> d;
double sum = a + b + c + d;
int prod = a * b * c * d;
double average = sum / 4;
cout << average << endl;
if (sum != average && average == sum) {
cout << "You're a goober!!" << endl;
} else {
cout << "You're still an goober :-P" << endl;
}
// if (Correct condition)
// return true;
// else Wrong condition
// return false
}
int main() {
while (GameBoy()) {
}
return 0;
}
I feel silly now. Just finished posting this question and found out what I needed to stop that endless loop. Once I added this then the issue stopped. Wow won't forget that!.
cin.clear();
cin.ignore();
the problem that in the main body the getwhattheywant function is executing twice what I want is this
getwhattheywant execute then the user entered one then if the user entered one do the summation operation but what is happening with me that it's reasking the user to enter a number.
#include <iostream>
using namespace std;
double dothesum(int x, int y)
{
int sum = x + y;
return sum;
};
int getwhatheywant()
{
int choice;
cout << "1- for sum " << endl;
cout << "2- for quit ";
cin >> choice;
return choice;
}
void the_sum()
{
int x, y;
cout << " enter the first number " << endl;
cin >> x;
cout << " enter the second number " << endl;
cin >> y;
cout << " the sum of the two number is " << dothesum(x, y) << endl;
}
int main()
{
int;
while (getwhatheywant() != 2) {
if (getwhatheywant() == 1) {
the_sum();
}
}
return 0;
}
Change your main():
int main()
{
int whatTheyWant;
while ( (whatTheyWant = getwhatheywant()) != 2) {
if (whatTheyWant) == 1) {
the_sum();
}
}
return 0;
}
This stores the value from a single call to getwhattheywant() so you can first see if they're asking to quit, and if not, you can see what else they might want. Now, I'd write it slightly differently:
bool working = true;
while(working) {
int choice = getWhatTheyWant();
switch(choice) {
case 1: the_sum(); break;
case 2: working = false; break;
}
}
I am a new contributor and here I am trying to make a simple calculator but having errors in my code. When I compile the code I get:
Error: C:\Users\IJLAL\Documents\collect2.exe [Error] ld returned 1 exit status while compiling
In case it could help, here is the screen shot of error when I pressed compile button or F11 in Dev C++:
Here is my code:
#include<iostream>
using namespace std;
void fun(float a, float b);
int main()
{
float a, b, sum, sub, mul, divide, mod;
char op;
//operands and operators are enterd by the user
cout<<"Enter any two operands with operator=";
cin>>a>>op>>b;
fun(a, b);
return 0;
}
void op(float a, float b)
{
if(a+b)
{
float sum=a+b;
cout<<"\nAddition of two numbers is="<<sum;
}
else if(a-b)
{
float sub=a-b;
cout<<"\nSubtraction of two numbers is="<<sub;
}
else if(a*b)
{
float mul=a*b;
cout<<"\nMultiplication of two numbers is="<<mul;
}
else if(a/b)
{
float divide=a/b;
cout<<"\nDivision of two number is="<<divide;
}
else
{
cout<<"\nInvalid operator.......";
}
}
Please tell me the solution of this problem, so that I can compile the code successfully. If there is any better solution to make a simple calculator on beginner level please mention it in answer.
You're not so far from a result. The problem is that you have not defined the function fun(). Furthermore, in the function op() that you have defined, you do not use the operator of the input.
So first thing to do is to change the signature of the function:
void fun(char op, float a, float b);
Then you need to invoke your function in main(), passing also the operation that was requested by the user:
fun(op, a, b);
Finally you need to change all your if to check if op is the matching operator:
void fun(char op, float a, float b)
{
if(op=='+')
{
...
}
else if(op=='-')
{
...
You should then get the expected result.
Online demo
Aditional infos
if (a+b) just calculates the expression using the two values of the user, and if it's non zero, it's considered as true.
once you got this program to work, you can look for the switch statement
You can use additional functions to make a better calculator. You can use this code. Hope this code will be helpful for you.
The header <iomanip> is part of the Input/output library of the C++ Standard Library and <math.h> is used when we perform mathematical operations.
#include<iostream>
#include<conio.h>
#include<math.h>
#include<iomanip>
char op;
using namespace std;
void sum()
{
int sum = 0;
int n;
int numberitems;
cout << "Enter number of items: \n";
cin >> numberitems;
for(int i=0;i<numberitems;i++)
{
cout<< "Enter number "<<i<<":\n\n" ;
cin>>n;
sum+=n;
}
cout<<"sum is: "<< sum<<endl<<endl;
}
void diff()
{
int diff;
int n1,n2;
cout<<"enter two numbers to find their difference:\n\n";
cout<<"enter first number:";
cin>>n1;
cout<<"\nenter second number:";
cin>>n2;
diff=n1-n2;
cout<<"\ndifference is:"<<diff<<endl<<endl;
}
void pro()
{
int pro=1;
int n;
int numberitems;
cout<<"enter number of items:\n";
cin>>numberitems;
for(int i=0;i<=numberitems;i++)
{
cout<<"\nenter item "<<i<<":";
cin>>n;
pro*=n;
}
cout<<"product is:"<<pro<<endl<<endl;
}
void div()
{
int div;
int n1;
int n2;
cout<<"enter 2 numbers to find their quotient\n\n";
cout<<"enter numerator:";
cin>>n1;
cout<<"\nenter denominator:";
cin>>n2;
div=n1/n2;
cout<<"\nquotient is:"<<div<<endl<<endl;
}
void power()
{
long int p;
int res=1,n;
cout<<"enter number:";
cin>>n;
cout<<"\nenter power:";
cin>>p;
for(int i=1;i<=p;i++)
{
res=n*res;
}
cout<<n<<"\n power "<<p<<" is :"<<res<<endl;
}
void sq()
{
float s;
int n;
cout<<"enter number to find its square root:";
cin>>n;
s=sqrt(n);
cout<<"\nsquare root of "<<n<<" is :"<<s<<endl;
}
void fact()
{
long int f=1;
int c=1,n;
cout<<"enter number to find its factorial:";
cin>>n;
while(c<=n)
{
f=f*c;
c+=1;
}
cout<<"\nfactorial of "<<n<<" is :"<<f<<endl;
}
void expo()
{
long double res=1,p;
double e=2.718281828;
cout<<"enter power of exponential function:";
cin>>p;
for(int i=1;i<=p;i++)
{
res=e*res;
}
cout<<" e^ "<<p<<" is :"<<res<<endl;
}
int main()
{
system("cls");
do
{
system("pause");
system("cls");
cout<<"***which operation you want to perform***\n";
cout<<"press 0 for exit\n";
cout<<"press 1 for addition \n";
cout<<"press 2 for subtraction\n";
cout<<"press 3 for multiplication\n";
cout<<"press 4 for division\n";
cout<<"press 5 for power calculation\n";
cout<<"press 6 for square root \n";
cout<<"press 7 for factorial calculation\n";
cout<<"press 8 for exponential calculation\n";
cout<<"press option:";
cin>>op;
switch(op)
{
case '1':
sum();
break;
case '2':
diff();
break;
case '3':
pro();
break;
case '4':
div();
break;
case '5':
power();
break;
case '6':
sq();
break;
case '7':
fact();
break;
case '8':
expo();
break;
case '0':
exit(0);
default:
cout<<"invalid input" ;
system("cls");
}
}
while(op!='0');
getch();
}
Hey I'm still a newbie on c++ but hope this would help, I used while loop to loop the calculator but I don't have a good error handler for example when users try to input a letter instead of numbers.
#include <iostream>
#include <cmath>
using namespace std;
int result (int a, int b, char op);
int main()
{
char optr, choice;
int nr1, nr2;
while (true){
cout << "Enter first number: ";
cin >> nr1;
cout << "Enter an operator (+ - / * %) : ";
cin >> optr;
cout << "Enter second number: ";
cin >> nr2;
result (nr1, nr2, optr);
cout<<"Would you like to perform other calculation?(Y/N): ";
cin >> choice;
if (choice =='N'||choice =='n'){
break;
}
}
}
int result (int a, int b, char op)
{
int result;
if (op == '+'){
result = a + b;
cout << "Result to " << a << " + " << b << " = " << result << endl;
} else if (op == '-'){
result = a - b;
cout << "Result to " << a << " + " << b << " = " << result << endl;
} else if (op == '*'){
result = a * b;
cout << "Result to " << a << " * " << b << " = " << result << endl;
} else if (op == '/'){
result = a / b;
a / b;
cout << "Result to " << a << " / " << b << " = " << result << endl;
} else if (op == '%'){
result = a % b;
cout << "Remainder to " << a << " % " << b << " = " << result << endl;
} else {
cout <<"Error 404: " << a << op << b <<" Wrong input format. Program terminated." << endl;
// i still dont know how to properly use error handling
}
}
I won't criticize your solution as I have a better solution as you mentioned "please mention a better solution in answer"
Here's my solution with comments to make you understand what each statement does.
#include <iostream>
using namespace std;
// I am going to show How to Design a program
// We have to break down our progress a bit by bit
// and do the progress of one thing with function
// For calculator we have to take input from user keyboard twice,
// And an opperator from user
int userInput() // this requires to get input from user keyboard
{
cout << "Enter a number: ";
int no{};
cin >> no;
return no;
}
char userOpr() // Using type char to store the ASCI Opperator means requires char to store +,*,/,-
{
cout << "Enter opperator: ";
char opr{};
cin >> opr;
return opr;
}
int calculate(int input1, char opper, int input2)
{
if (opper == '+')
{
return input1 + input2;
}
else if (opper == '-')
{
return input1 - input2;
}
else if (opper == '*')
{
return input1 * input2;
}
else if (opper == '/')
{
return input1 / input2;
}
return 0;
}
int main()
{
// get the first no. from user
// getUserInput();
// get the math oppperator from the user
// getMathOpperator();
// get the second no. from the user
// getUserInput();
// calculate the values
// calculateResults();
// print out the results
// printResults();
cout << "Hello This is a simple calculator program Designed by Shankhui!\n\n";
while (true)
{
int input1{ userInput() };
int input2{ userInput() };
char opper{ userOpr() }; // Using type char to store the ASCI Opperator means requires char to store +,*,/,-
cout << input1 << " " << opper << " " << input2 << " = " << calculate(input1, opper, input2) << '\n' << '\n';
}
return 0;
}
Just copy this code and modify however you want to.
#include <iostream>
int main() {
int math_ques_1, math_ques_2;
std::cout << "What is the base of the question?" << std::endl;
std::cin >> math_ques_1;
std::cout << "What do you want to add to the base?" << std::endl;
std::cin >> math_ques_2;
std::cout << "The answer is " << math_ques_1 + math_ques_2 << "." << std::endl; }
I am writing a program that asks a user for a difficulty level then gives them multiplication questions while counting the correct answers. My issue is my counter (numCorrect) updates for false answers too and I can't understand why. Can someone tell me why?
int main()
{
int n; //difficulty level
int a, b, atimesb; // random generated numbers and multiplication
string name;
int numCorrect=0; // initilize counter to 0
int numAsked=0; // initilize counter to 0
int exitCond = 1; // loop condition continue
cout << "this program tests your multiplication skills!" << endl;
cout << "what is your name?" << endl;
getline(cin, name);
cout << " Enter a difficulty level" << endl;
cin >> n; // user input for difficulty level
while (exitCond != 0) // loop to continue asking until user ends with 0
{
MakeQuestion(n, a, b, atimesb); // calls function to make a question
UserAnswerIsCorrect(a, b, atimesb); // calls function to ask question and evaluate it
if (UserAnswerIsCorrect) // update if correct
{
numCorrect++;
}
numAsked++; // update total questions
cout << " Enter 0 to quit, 1 to go again" << endl;
cin >> exitCond; // user input for difficulty level
}
PrintScore(numCorrect, numAsked); // calls function to print score
return 0;
}
int NewRandomNumber(int n)
{
int val;
val = rand() % n + 2; // creates a number between 2 and n
return val;
}
void MakeQuestion(int n, int& a, int& b, int& atimesb)
{
a = NewRandomNumber(n);
b = NewRandomNumber(n);
atimesb = a*b;
return;
}
bool UserAnswerIsCorrect(int a, int b, int atimesb)
{
int userAns;
cout << a << "X" << b << "=" << endl;
cin >> userAns;
if (userAns == atimesb)
{
cout << "Correct!";
return true;
}
else
{
cout << "false, correct answer is:" << atimesb << endl;
return false;
}
}
void PrintScore(int numCorrect, int numAsked)
{
cout << "your score is: " << numCorrect << "/" << numAsked << " or " <<
(numCorrect / numAsked) * 100 << "%" << endl;
return;
}
UserAnswerIsCorrect(a, b, atimesb); // calls function to ask question and evaluate it
if (UserAnswerIsCorrect) // update if correct
{
numCorrect++;
}
should be
if (UserAnswerIsCorrect(a, b, atimesb)) // update if correct
{
numCorrect++;
}
You ignored the return value of UserAnswerIsCorrect in your code.
You can do this
bool corr;
corr = UserAnswerIsCorrect( a, b, atimesb);
if(corr) {
numCorrect++;
}
Although it just happened because you was ignoring the return value.
try this condition
if(UserAnswerIsCorrect == true){
....
}
Ok i've been programming for about a week now, i started with c++. I'm writing a program that is a kind of an arithmetic trainer, you enter the amount of equations you want, you enter your limit for the random number generator, you specify what kind of equations you want(/*-+), then the program uses a for loop and goes through and generates the equations and their answers in a var and then the users input is checked against this var and if they match another var which is counting the right answers is incremented. After the last equation the program tells the user how many they got right out of how many equations, and by dividing the amount of right answers by the amount of questions then multiplying this value by 100 u should obtain the accuracy percentage for this users arithmetic session. Problem is c++ keeps returning to me a friggin 0 value and i cannot for the life of me work out why in the world c++ is doing this.
entire program:
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;
void menu(void);
class session{
public:
session(){
create_session();
}
void create_session(void){
amount = 0;
range_limit = 0;
rights = 0;
answer = 0;
input = 0;
type = "";
while(amount == 0){
cout << "\nHow many equations do you want?: "; cin >> amount;
if(amount < 1){
cout << "\nAmount is too low!";
amount = 0;
}
}
while(range_limit == 0){
cout << "Enter the number range limit: "; cin >> range_limit;
if(range_limit < 1){
cout << "\nRange limit too low!";
range_limit = 0;
}
}
while(type == ""){
cout << "What equation type do you want?: "; cin >> type;
int strlen = type.size();
if(strlen < 1){
cout << "Invalid type input!";
type = "";
}
}
if(type == "+"){
for(int i=0;i<amount;i++){
int a = random();
int b = random();
answer = a + b;
cout << "\n" << a << " + " << b << " = "; cin >> input;
if(answer == input){
rights++;
}
}
}
cout << "\nYou got " << rights << " answers right out of " << amount << " equations." << endl;
cout << "Accuracy percentage: " << getAccuracy() << "%" << endl;
int post_menu=0;
while(post_menu == 0){
cout << "Enter 1 to create another session or 2 to return to the menu: ";
cin >> post_menu;
if(post_menu == 1){
create_session();
}else if(post_menu == 2){
menu();
}else{
cout << "Invalid input: ";
post_menu = 0;
}
}
}
float getAccuracy(){
float x = (rights/amount)*100;
return x;
}
int random(){
int x = 1+(rand()%range_limit);
return x;
}
void set_amount(int a){
amount = a;
}
void set_range_limit(int r){
range_limit = r;
}
void set_rights(int R){
rights = R;
}
void set_answer(int a){
answer = a;
}
void set_input(int i){
input = i;
}
void set_type(string t){
type = t;
}
private:
int amount;
int accuracy;
int range_limit;
int rights;
int answer;
int input;
string type;
};
int main(){
cout << "=== WELCOME TO ARITH! === \n=========================\n";
menu();
return 0;
}
void menu(void){
//Set the seed for random number gen.
srand(time(0));
//Set var for getting menu input, then get the menu input..
int menu_input;
cout << "\n[1]Create a Session. [2]Exit Arith. \nWhat would you like to do?: ";
cin >> menu_input;
//Now we check what the user wants and act accordingly..
if(menu_input > 2){
cout << "error";
menu_input=0;
}else if(menu_input == 1){
session start;
}else if(menu_input == 2){
cout << "\nExiting Arith!";
}else{
cout << "error";
menu_input=0;
}
}
Troublesome part:
float getAccuracy(){
float x = (rights/amount)*100;
return x;
some how the program is returning 0%.
anyone know why this is so and how to get the result im after.
rights and amount both are int , so when you divide the value is floored, for example if you do 5/2 the answer would be 2 instead of 2.5. To solve this you need to cast one of the variable to float like this: (float(rights)/amount) * 100.
when two int numbers are divided the result will also be int even if temporary variable. so you can make any of the variable float or double or cast it.
You need to convert only one data type because the other will be type promoted implicitly.
float x = ((double)rights/amount)*100;
or you can make your amount variable float by default if it doesnt affect any other part of your code.
Also you have the option to static cast:
float x = (static_cast<double>(rights)/amount)*100;