-1

我试着做一个非常简单的计算器。到目前为止,这就是我所拥有的,但我得到的答案真的很模糊。就像,将 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;
    }

}
4

2 回答 2

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) 的变量。

于 2013-10-27T22:15:54.877 回答
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;
于 2013-10-27T22:16:25.140 回答