为什么方法不起作用? [英] Why methods don't work?
问题描述
我正在对计算器进行编程,例如当我选择第一个选项时,程序将停止.我不能输入任何数字. 我必须在代码中进行哪些更改才能使方法起作用? 我不知道该怎么办.
I'm programming a calculator and when I choose for example first option, program stops. I can't enter any numbers. What do I have to change in my code to make the methods work? I don't know what I have to do.
main.cpp:
#include "stdafx.h"
#include <iostream>
#include "Calculator.h"
using namespace std;
float Calculator::add()
{
cout << "Enter 1 number: ";
cin >> a;
cout << "Enter 2 number: ";
cin >> b;
system("cls");
cout << a + b << endl;
return 0;
}
float Calculator::sub()
{
cout << "Enter 1 number: ";
cin >> a;
cout << "Enter 2 number: ";
cin >> b;
system("cls");
cout << a - b << endl;
return 0;
}
float Calculator::mul()
{
cout << "Enter 1 number: ";
cin >> a;
cout << "Enter 2 number: ";
cin >> b;
system("cls");
cout << a*b << endl;
return 0;
}
float Calculator::div()
{
cout << "Enter 1 number: ";
cin >> a;
cout << "Enter 2 number: ";
cin >> b;
system("cls");
cout << a / b << endl;
return 0;
}
int main()
{
int choose;
Calculator k1;
cout << "1.Add\n";
cout << "2.Sub\n";
cout << "3.Mul\n";
cout << "4.Div\n";
cout << "Choose: ";
cin >> choose;
if (choose == '1')
k1.add();
else if (choose == '2')
k1.sub();
else if (choose == '3')
k1.mul();
else if (choose == '4')
k1.div();
system("pause");
return 0;
}
Calculator.h:
Calculator.h:
#pragma once
#ifndef Calculator_h
#define Calculator_h
class Calculator {
private:
float a, b;
public:
float add();
float sub();
float mul();
float div();
};
#endif
推荐答案
您正在阅读将select作为一个整数:int choose;
,因此您必须将其视为一个整数:
You are reading choose as an int: int choose;
so you have to treat it as one:
if (choose == 1)
k1.add();
else if (choose == 2)
k1.sub();
else if (choose == 3)
k1.mul();
else if (choose == 4)
k1.div();
按要求说明:
if (choose == '1')
从语法上来讲,这并没有错,因为简单地C ++是隐式广播字符'1'为其 ASCII码,它是一个值49的整数.
This is not wrong syntactically speaking because simply C++ is casting implicitly the char '1' to its ASCII code which is an int of value 49.
您实际上是在执行以下操作:if (choose == 49)
而不是if (choose == 1)
You were literally doing the following: if (choose == 49)
instead of if (choose == 1)
这篇关于为什么方法不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!