我该如何解决这个问题
How can I fix this?
using namespace std;
//a class that will handle all the calculations requested by user
class MathOperations{
public:
void Message();
int setSum(int,int);
int setSuB(int,int);
int setMul(int,int);
float setDiv(float,float *);
int setSqrt(int);
};
//Implementation:
void MathOperations:: Message(){
cout<< " Welcome. This program simulates a calculator "<<endl;
}
// implementing the setters methods.
int MathOperations::setSum(int a, int b){
int total;
total = a + b;
return total;
}
int MathOperations:: setSuB(int a, int b){
int total;
total = a - b;
return total;
}
int MathOperations:: setMul(int a, int b){
int total;
total = a * b;
return total;
}
float MathOperations:: setDiv(float a, float *b){
float result;
if(b ==0){
cout << "Using the Default Value of 1 because you can't devide by 0"<<endl;
}
else
result = (a / *b);
return result;
}
int MathOperations::setSqrt(int Square){
int total;
total = sqrt(Square);
return total;
}
int main(int argc, const char * argv[])
{
//creating instances of class MathOperations
MathOperations add, sub, mul, div, sqrt;
///creating variable to hold user input
int fnum;
float snum;
char opt= '0';
//propt user for values
cout << " Enter a Number"<<endl;
cin >> fnum;
cout << " Enter a second number " <<endl;
cin >> snum;
float total = div.setDiv(fnum, &snum);
cout << total <<endl;
cout << " What would you like to do '+','-','*','/' ?"<<endl;
cin >> opt;
switch (opt) {
case '+' :
{
int total = add.setSum(fnum, snum);
cout << " The Total Sum of both numbers is " << total <<endl;
}
break;
case '-' :
{
int total = sub.setSuB(fnum, snum);
cout << " The Subtraction of both Numbers is " << total << endl;
}
break;
case '*' :
{
int total = mul.setMul(fnum, snum);
cout << " The Multiplication of both Numbers is " << total << endl;
}
break;
case '/' :
{
int total = div.setDiv(fnum, &snum);
cout << " The Division of both Numbers is " << total <<endl;
}
default:
cout << " Not a valid Option"<<endl;
}
}
该部门无法正常工作。我在这里做错了什么?我正在尝试创建一个包含数学运算的类。我是一个初学者,试图在这里做一些练习。你能告诉我我具体做错了什么吗?
函数div 的第二个参数不应该是指针。至少我看不出有任何理由把它作为一个指针。
因此,只需从变量 snum 中删除 * 和 & 即可。
在 setDiv 函数中,您不会保护自己免受 0 的除法,因为您没有首先将第二个浮点数与 0 进行比较。您只是将其地址与 NULL 进行比较。
错误消息没有意义:程序不会以任何方式"使用 1"。
如果指针恰好为 NULL,则返回一个未初始化的值。
当你说你使用的是 1 而不是 0 时,你永远不会将 b 的值更改为 1。
相关文章:
- Project Euler问题4的错误解决方案
- 在java中解决这段代码时面临循环中的问题
- C++:Application.cpp中抛出了未解析的外部符号(解决方案在问题的末尾,供未来的读者参考)
- 难以理解某些人解决IOI问题的源代码
- 节俭并发:未解决的外部问题
- IpOpt拒绝解决不受约束的问题
- 如何解决这个超硬恒星的创造问题
- 循环无限运行C++解决骑士之旅问题
- 使用 bfs 解决连接组件问题时得到错误的答案
- 如何解决 Ninja c++ 构建和执行问题
- 无法在问题解决方案中执行输出逻辑
- 如何在不到O(N)的时间内解决这个问题?
- Arduino 用于语句错误。令牌之前的预期')' ';'。如何解决这个问题?
- 移动赋值运算符;尝试引用已删除的函数.我该如何解决这个问题?
- 如何在不使用额外空间的情况下解决这个问题?
- 我无法在Visual Studio代码中使用CIN输入答案,它说输入您的年龄,但它说只读文本编辑器如何解决这个问题?
- 最大的回文产品 - 程序未运行,编写解决方案但无法理解问题
- 如何解决"no Qt platform plugin could be initialized"问题?
- 如何解决可能的唯一组合问题
- Windows上的模板有什么问题?解决方案是什么