【发布时间】:2012-07-15 22:27:14
【问题描述】:
对编码非常陌生,所以请理解 ;)
我基本上是在尝试使用while 循环和if 语句制作一个计算器。
#include <iostream>
using namespace std;
int x = 1;
int number;
int total = 0;
int amt = 1;
int a;
int b;
int c;
int d;
string ans;
class OperateClass
我收到错误:'main' 声明中有两个或多个数据类型
请解释这意味着什么/如何解决它。
我还想知道是否需要为每个函数(加、减、乘和除)创建一个新对象
请帮忙!
int main()
{
cout << "Do you want to add, subtract, multiply or divide? I want to : " << endl;
cin >> ans;
if(ans == "add"){
OperateClass opOper;
opOper.add();
}else{
if(ans == "subtract"){
OperateClass opOper
opOper.subtract();
}
}else{
if(ans == "multiply"){
OperateClass opOper
opOper.multiply();
}
}else{
if(ans == "divide"){
OperateClass opOper
opOper.divide();
}
}
}
class OperateClass{
public:
int add(){
while(x <= 3){
cout << "Enter a number to use to add: " << endl;
cin >> a;
total = total + a;
x++;
amt++;
}
}
int subtract(){
while(x <= 3){
cout << "Enter a number to use to add: " << endl;
cin >> b;
total = total - b;
x++;
amt++;
}
}
int multiply(){
while(x <= 3){
cout << "Enter a number to use to add: " << endl;
cin >> c;
total = total * c;
x++;
amt++;
}
}
int divide(){
while(x <= 3){
cout << "Enter a number to use to add: " << endl;
cin >> d;
total = total / d;
x++;
amt++;
}
}
}
int print(){
cout << "Your total is: " << total << endl;
return 0;
}
【问题讨论】:
-
你应该使用 if-else if-else 或 switch。你现在正在做的事情令人困惑。很难找到打开和关闭括号。
-
那些遍地的全局变量真的不是个好主意。
-
在 "if(ans == "subtract"/"multiply"/"divide")" 你忘记了 ";"在“操作类 opOper”之后
-
好的,我不再收到分号错误
-
编写
if/else if/ 序列的常用方法是将“else if”视为一个单词。我无法在评论中正确格式化它,但this gist 显示了更传统的方式来做到这一点。 (有些语言甚至有elsif或elseif作为关键字;C++ 没有。)
标签: c++ function if-statement while-loop declaration