我试着制作一个非常简单的计算器。到目前为止,这就是我所拥有的,但我得到了非常模糊的答案。比如,对于乘以2和2我得到1550532996.所有帮助赞赏。
#include <iostream>
using namespace std;
int main()
{
int x;
int b;
int k;
int sum=x+b;
int difference=x-b;
int product=x*b;
int quotient=x/b;
cout<<"Enter a number"<<endl;
cin>>x;
cout<<"Enter another number."<<endl;
cin>>b;
cout<<"What do you want to do with these numbers? Enter 1 for addition, 2 for subtraction, 3 for multiplication, and 4 for division"<<endl;
cin>>k;
switch (k){
case 1:
cout<<sum<<endl;
break;
case 2:
cout<<difference<<endl;
break;
case 3:
cout<<product<<endl;
break;
case 4:
cout<<quotient<<endl;
break;
}
}
答案 0 :(得分:1)
替换
int x;
int b;
int k;
int sum=x+b;
int difference=x-b;
int product=x*b;
int quotient=x/b;
cout<<"Enter a number"<<endl;
cin>>x;
cout<<"Enter another number."<<endl;
cin>>b;
cout<<"What do you want to do with these numbers? Enter 1 for addition, 2 for subtraction, 3 for multiplication, and 4 for division"<<endl;
cin>>k;
通过
int x;
int b;
int k;
cout<<"Enter a number"<<endl;
cin>>x;
cout<<"Enter another number."<<endl;
cin>>b;
cout<<"What do you want to do with these numbers? Enter 1 for addition, 2 for subtraction, 3 for multiplication, and 4 for division"<<endl;
cin>>k;
int sum=x+b;
int difference=x-b;
int product=x*b;
int quotient=x/b;
int sum = x + b不是函数,只是设置为(x + b)的变量。
答案 1 :(得分:1)
问题在于您在读取用户输入之前进行了计算。由于你的变量是未初始化的,它们会保留一些随机的东西(可能是之前在内存中的那个位置)。这就是你得到错误结果的原因。
int x;
int b;
int k;
int sum=x+b;
int difference=x-b;
int product=x*b;
int quotient=x/b;
cout<<"Enter a number"<<endl;
cin>>x;
cout<<"Enter another number."<<endl;
cin>>b;
cout<<"What do you want to do with these numbers? Enter 1 for addition, 2 for subtraction, 3 for multiplication, and 4 for division"<<endl;
cin>>k;
应该改为:
int x;
int b;
int k;
cout<<"Enter a number"<<endl;
cin>>x;
cout<<"Enter another number."<<endl;
cin>>b;
int sum=x+b;
int difference=x-b;
int product=x*b;
int quotient=x/b;
cout<<"What do you want to do with these numbers? Enter 1 for addition, 2 for subtraction, 3 for multiplication, and 4 for division"<<endl;
cin>>k;