C++ total keeps going up - c++

Hello this is my first program with a do-while loop and its taken me a little while to get it down. I need to have the user enter 2 numbers, and raise the first number to the second number. I have finally got the coding to ask if "they would like to raise another number by a power?" and when they say yes and enter 2 new numbers the total adds the total from the first 2 numbers entered with the second set of numbers and so on. Can someone help me out with this problem? Here is the coding and a picture to help y'all out!
#include <iostream>
using namespace std;
int main()
{
int num;
int pow;
int p;
int power = 1;
char yesno = 'y' || 'Y';
do
{
cout << "Enter a number: ";
cin >> num; "\n";
cout << "Enter the power to raise: ";
cin >> pow; "\n";
for (p = 1; p <= pow; p++)
{
power = power * num;
}
cout << "The total is: " << power << endl;
cout << "\n\n";
cout << "Would you like to raise another number by a power? [Y/N]";
cin >> yesno;
} while (yesno != true);
}

The problem of the ever-increasing answer is that power is not being reset inside the do-while loop, so the last value is being carried forward into the next loop. You need reset it at the top of the loop.
Another problem with the code is that the exit condition would never occur.
Try this instead:
int main()
{
int num;
int pow;
int p;
int power;
char yesno;
do
{
power = 1; // <<<<<< reset power here
cout << "Enter a number: ";
cin >> num; "\n";
cout << "Enter the power to raise: ";
cin >> pow; "\n";
for (p = 1; p <= pow; p++)
{
power = power * num;
}
cout << "The total is: " << power << endl;
cout << "\n\n";
cout << "Would you like to raise another number by a power? [Y/N]";
cin >> yesno;
} while (yesno == 'y' || yesno == 'Y'); // <<<<< test for 'yes' response
}

When you reach line } while (yesno != true); and loop back to do {, the variable power still holds the previous num^pow. You will need to assign power = 1 after do {.

#include <iostream>
// you also need
#include <cmath> // for pow()
using namespace std;
int main()
{
// int num; Declare variables where they're used. As locally as possible.
// int pow;
// int p;
// int power = 1;
// char yesno = 'y' || 'Y'; I don't know what you were trying to do here
// the expression 'y' || 'Y' will always be true
// and evaluate to some value different from null
// wich will be assigne to yesno. But with no con-
char yesno; // sequences since it later gets overwritten by
do // cin >> yesno; There is no need to initialize
{ // this variable.
cout << "Enter a number: ";
int num;
cin >> num; "\n"; // the statement "\n"; has no effect.
cout << "Enter the power to raise: ";
int pow;
cin >> pow; "\n"; // again. no effect.
// for (p = 1; p <= pow; p++) as user4581301 has pointed out in the
// comments it is more ... natural in C
// to loop from 0 to < max:
int power = 1; // now its time to declare and define power ;)
for(int p = 0; p < pow; ++p) // notice that you can declare variables
{ // in the init-statement of a for-loop
// power = power * num; shorter:
power *= num;
}
cout << "The total is: " << power << /* endl; + 2 x '\n' gives: */ << "\n\n\n";
// cout << "\n\n";
cout << "Would you like to raise another number by a power? [Y/N]";
cin >> yesno;
// } while (yesno != true); that condition will most likely always be true
// since the user would have a hard time to input
// a '\0' character, which would evaluate to false
// better:
} while(yesno == 'y' || yesno == 'Y' );
}
done.
Without clutter:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
char yesno;
do {
cout << "Enter a number: ";
int num;
cin >> num;
cout << "Enter the power to raise: ";
int pow;
cin >> pow;
int power = 1;
for(int p = 0; p < pow; ++p)
power *= num;
cout << "The total is: " << power << "\n\n\n";
cout << "Would you like to raise another number by a power? [Y/N]";
cin >> yesno;
} while(yesno == 'y' || yesno == 'Y' );
}

Related

How to print product of all inputted numbers using a loop?

int main() {
cout << "Enter some numbers fam! " << endl;
cout << "If you wanna quit, just press q" << endl;
int n{ 0 };
int product = 1;
char quit = 'q';
while (n != 'q') {
cin >> n;
product = product* n;
cout <<"The product is : " << product << endl;
}
cout << endl;
cout << product;
return 0;
}
Whenever I print it out and cut the code using 'q', it prints me an infinite amount of "The product is 0". Also, how can I print out the final product of all numbers at the end?
So, there are some problems in your code.
First, you are taking input and assigning it to an int, which might not have been a problem, but you are also comparing the int to a char(which will cause problems in your case)
int n{ 0 };
while(n != 'q') {
cin >> n;
}
To solve that, you can make the n a string and then convert it into an integer with stoi(n) to use with the calculation
string n; // don't need to initialize a string, they are initialized by default.
int product = 1;
cin >> n; // Taking input before comparing the results
while(n != "q") { // Had to make q a string to be able to compare with n
product *= stoi(n); // Short for product = product * stoi(n)
cout <<"The product is : " << product << endl;
cin >> n; // Taking input for the next loop round
}
cout << endl;
cout << product;

alphabetic inputs run infinite loop

I wrote a function to squire number and try to cover all the input possibilities.
Overall it works fine with numeric input, but it starts a infinite loop of printing statements on screen when I enter alphabetical input.As all we know that inside computer single character like "A or a or b or B" so on is represented by integers and as i learned from my teacher that we can store single characters into a variable with integer data type. i am not talking about strings which means collection of characters . this program create problem with single character !
#include <iostream>
#include <string>
using namespace std;
void squire();
int main() {
squire();
}
void squire() {
double num = 1.0, pow = 1.0, Squire_Number = 1.0;
char ans;
reStart:
cout << "please Enter the Number: \n";
cin >> num;
cout << "please enter the nmber you want to power the number with: \n";
cin >> pow;
if (num > 0 && pow>0) {
for (int i = 1; i <= pow; i++) {
Squire_Number *= num;
}
cout << pow << " power of " << num << " is equil to : " << Squire_Number;
goto option;
}
else
{
cout << "Please enter Positve Integers. \n" ;
option:
cout<< "\nPease type 'Y' to Enter the values again OR type 'c' to Exit ! \n";
cin >> ans;
if (ans == 'y' || ans == 'Y') {
goto reStart;
} else if (ans == 'c' || ans == 'C') {
cout << "thank you for using our function. \n";
}
}
return;
}
Better try to read the input in an std::string, then parse the string to check if you only have numeric characters and then use std::atoi to convert the string in integer. One last recomendation, avoid to use goto instructions, this practice make a code difficult to read.
#include <iostream>
#include <string>
#include <cstdlib>
bool OnlyNumeric(const std::string& numStr)
{
size_t len= numStr.length();
int i;
for (i=0;i<len && numStr[i] <='9' && numStr[i] >='0';i++) ;
return i == len;
}
int main()
{
std::string inputStr;
int num;
do{
std::cout << "Input number:\n";
std::cin >> inputStr;
}
while (!(OnlyNumeric(inputStr) && (num=std::atoi(inputStr.c_str())) ));
std::cout << "Your number is : " << num;
return 0;
}

error: variable was not declared in this scope c++

I want to write the programm, that takes two numbers m and n as input and gives n-th digit of m number. Example m=1358 n=2 Output: 5
#include <iostream>
#include <string>
using namespace std;
int main(){
while(true){
int m = 0,n = 10;
char check;
while(true){
cout << "Enter please number m and which digit you want to select";
cin >> m >> n;
string m_new = to_string(m);
if(m_new.length() > n)
break;
else
cout << "n must be less than or equal to m";
}
cout << "The position" << n << "Of integer" << m << "is:" << m_new.substr(n,1);
cout << "Do you want to try again?(y/n)\n";
cin >> check;
while(check != 'y'&& check != 'n'){
cout <<"Please enter y or n\n";
cin >> check;
}
if(check == 'n'){
break;
}
}
return 0;
}
But i got an error: 'm_new' was not declared in this scope. Why do I get this error and how to fix it?
The m_new variable is local to nested while loop and can't be used outside of its scope. Scope represented by braces {} determines visibility:
int main() {
// can't be used here
while (true) {
// can't be used here
while (true) {
string m_new = to_string(m);
// can only be used here
}
// can't be used here
while (check != 'y'&& check != 'n') {
// can't be used here
}
// can't be used here
}
// can't be used here
}
Rethink the design to use only one while loop:
int main(){
char check = 'y';
while (std::cin && choice == 'y') {
int m = 0, n = 10;
std::cout << "Enter please number m and which digit you want to select";
std::cin >> m >> n;
string m_new = to_string(m);
// the rest of your code
std::cout << "Please enter y or n\n";
std::cin >> check;
}
}
Now the m_new variable is visible to everything inside the while loop.
m_new is declared inside the while loop. Anything declared inside a {...} block will only exist inside that block. The final use of it:
cout << "The position" << n << "Of integer" << m << "is:" << m_new.substr(n,1);
is outside the block, and therefore the variable no longer exists.
The variable "m_new" was just in the "while(true)" scope, and when your're asking this variable out of loop, it throws a compile-time error.
while(true){
...
string m_new = to_string(m);
...
}
...
cout << "The position" << n << "Of integer" << m << "is:" << m_new.substr(n,1);
^
...

How to use looping in C++

I am new to C++ and I am making a program to generate a multiplication table. Here is he code.
#include <iostream>
using namespace std;
int main()
{
int num;
cout << "Enter a number to find Multiplication Table ";
cin >>num;
for(int a=1;a<=10;a++)
{
cout<<num<<" x "<<a<<" = "<<num*a<<endl;
}
cout << "Press ENTER to continue...\n";
cin.get();
getchar();
return 0;
}
I want that after the multiplication table of one number is displayed , the user should have an option of entering another number or exiting.
Like press "n" to enter a new number or "e" to exit
This may be what you want. (this is the implementation of main function)
int num;
char command;
bool exit=false;
while(!exit)
{
cout << "Enter a number to find Multiplication Table ";
cin >>num;
for(int a=1;a<=10;a++)
{
cout<<num<<" x "<<a<<" = "<<num*a<<endl;
}
cout << "Press n to continue or e to exit\n";
cin >> command;
while(command != 'n' && command != 'e')
{
cout << "Just press n to continue or e to exit!\n";
cin >> command;
}
if (command == 'e')
{
exit=true;
}else
{
exit=false;
}
}
return 0;
#include <iostream>
using namespace std;
int main()
{
int num;
char ch;
do{
cout << "Enter a number to find Multiplication Table";
cin >> num;
for(int a=1;a<=10;a++)
{
cout<<num<<" x "<<a<<" = "<<num*a<<endl;
}
cout << "Press \"n\" to enter a new number or \"e\" to exit\n";
}while(cin>>ch && ch=='n');
return 0;
}

c++ Division . seemingly simple thing driving me crazy, advice please

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;