【问题标题】:Calculator program that I just created in c++ does only addition! Whats wrong with my code?我刚刚在 c++ 中创建的计算器程序只做加法!我的代码有什么问题?
【发布时间】:2015-09-17 16:56:58
【问题描述】:

我用 c++ 制作了一个计算器程序(在 learncpp.com {section 1.10a} 看到一个模型之后)

创建它是为了加、减、乘、除...

但它总是将给定的两个数字相加。

它编译得很好,但只会添加!即使我在选择运算符时选择了任何数字(即 1 表示添加,2 表示子等),如 2,3 甚至 25 或 2678,它只会添加两个给定的数字......(它只能添加我选了1对吗?)

我花了几个小时试图解决,但我对 c++ 太陌生了,我不知道怎么解决!

请大家帮忙...

这是我的程序

#include "stdafx.h"
#include <iostream>

int GetNo()
{
    std::cout << "Enter your Number: ";
    int a;
    std::cin >> a;
    return a;
}

int GetOp()
{
    std::cout << "Your Operator?" << std::endl;
    std::cout << "  (1 = +)" << std::endl;
    std::cout << "  (2 = -)" << std::endl;
    std::cout << "  (3 = *)" << std::endl;
    std::cout << "  (4 = /)" << std::endl;
    int o;
    std::cin >> o;
    return o;
}

int Calc(int x, int op, int y)
{
    if (op == 1);
        return x + y;
    if (op == 2);
        return x-y;
    if (op == 3);
        return x*y;
    if (op == 4);
        return x/y;

        return -1;

}

void PRINT(int q)
{
    std::cout << "Therefore, Your Result is, " << q << std::endl;
}

int main()
{
    int x = GetNo();
    int opr = GetOp();
    int y = GetNo();
    int q = Calc(x,opr,y);
    PRINT(q);
}

TQ 伙计们!我正在等待有用的回复... 如果可能的话,更详细一点......(因为我是 cpp 新手)

【问题讨论】:

  • 为什么要使用数字而不是字符本身?
  • if (op == 1); => if (op == 1) 没有;。无处不在。
  • 当您使用调试器单步执行代码时,结果如何?
  • 哦,非常感谢我让它工作了!!!!!!!!!!!!!!!!!!
  • 不知道为什么要关闭投票。问题有代码、预期行为(减法/除法/乘法)和实际行为(总是加法)。在这种情况下,调试器没有帮助,因为它只是显示实际行为是实际行为,即加法。 return x+y 总是被执行。调试器无法告诉您为什么

标签: c++ calculator


【解决方案1】:

当你放一个 ;在 if 子句之后意味着 if 是一个空块。因此无论语句是真还是假,if 旁边的语句总是被执行。所以你的代码

   if (op == 1);
    return x + y;

计算为:

  if (op == 1)
      {            //empty block
      }
  return x + y; // Outside if statement

因此总是返回加法。

【讨论】:

    【解决方案2】:
        if (op == 1);//this semicolon makes the statement end here so it tests the condition and ends the statement 
        return x + y;//so this is an independent statement and will always be executed
    

    所以删除所有if(condition)语句末尾的分号

    【讨论】:

      【解决方案3】:

      您的代码具有以下内容:

      int Calc(int x, int op, int y) { 如果 (op == 1); 返回 x + y; 如果(操作 == 2); 返回 x-y; if (op == 3);

      问题是 ;在if (op == 1); 之后。这正在被评估并且没有发生任何事情,那么你总是在执行return x + y;

      更好的循环方式是始终包含括号,这样这些简单的错误就不太常见了,例如:

      如果(操作==1) { 返回 x + y; }

      【讨论】:

        【解决方案4】:

        你的错误在calc()Function。看看:

        int Calc(int x, int op, int y)
        {
        if (op == 1);  //the ; is not needed, remove it! 
            return x + y;
        //same happens with the rest of the conditions, remove all semicolons after the if conditions 
        //...
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-05-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多