I'm trying to make a simple calculator in C++. Here is a portion of the code:
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int main()
{
int math;
int a1;
int a2 = 0;
int a3 = 1;
int answer;
int amount = 0;
int achecker = 1;
cout << "Welcome to my calculator! Type '1' to add, type '2' to subtract, "
"type '3' to multiply, type '4' to divide, and type '5' to exit."
<< endl;
cin >> math;
while (math = 1)
{
cout << "Input how many numbers you wish to add:" << endl;
cin >> amount;
achecker = amount;
do
{
cout << "Input the number you wish to add:" << endl;
cin >> a1;
answer = a1 + a2;
a2 = a1;
achecker = achecker - achecker + 1;
} while (achecker < amount);
cout << answer;
}
The problem I am encountering is that when the program gets into the do-while loop, it never comes out, it just keeps on asking for the user to input a number. I have gone over this several times and I have no idea what the problem is. Can someone help?
First of all , you should be writing while(math==1) sicnce math=1 is an assignment operator not a check operator.
Secondly, instead of while , use if since you want to do the calculation for addition only once , putting it in while loop will make it an infinite loop.
Thirdly , in the do - while loop , the condition should be while(achecker>=0), because your condition will always give a true value.So, actually , there is no need of achecker, simply keep decrementing amount by one for each loop run and keep the condition as while(amount>=0) .
One, more improvement i would like to suggest , though not required - declare answer as int answer = 0;. For each loop run , accept a new value in a1 and then for adding , write answer=answer+a1. This should serve your purpose.
So, edited code according to me should be -
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int main()
{
int math;
int a1;
int a3 = 1;
int answer = 0;
int amount = 0;
int achecker = 1;
cout << "Welcome to my calculator! Type '1' to add, type '2' to subtract, type '3' to multiply, type '4' to divide, and type '5' to exit." << endl;
cin >> math;
if(math == 1){
cout << "Input how many numbers you wish to add:" << endl;
cin >> amount;
do{
cout << "Input the number you wish to add:" << endl;
cin >> a1;
answer = answer + a1;
amount = amount - 1;
}while(amount>=0);
cout << answer;
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다