简体   繁体   English

为什么方法不起作用?

[英]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: 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

You are reading choose as an int: int choose; 您正在阅读select作为一个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();

Explanation as requested: 要求说明:

if (choose == '1')

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. 从语法上来讲,这并没有错,因为简单地C ++ 隐式地将char'1'转换为其ASCII代码 (值为49的int)。

You were literally doing the following: if (choose == 49) instead of if (choose == 1) 您实际上是在执行以下操作: if (choose == 49)而不是if (choose == 1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM