C++ 常量字符
Posted
技术标签:
【中文标题】C++ 常量字符【英文标题】:C++ Constant char 【发布时间】:2013-05-08 03:10:06 【问题描述】:我用 c++ 构建了一个简单的计算器,它使用字符,因此 (+,-*,/) 可以用作数学运算符,但是当用户输入“=”时它就不起作用了。
#include <iostream>
#include <string>
#include <sstream>
#include <math.h>
using namespace std;
#define PI 3.14159265359
#define NEWLINE '\n'
void printf(string string)
cout << string;
int main ()
char operation;
double a,b,c, value;
double answer = 0;
bool more = true;
cout << "Welcome to My Calculator\n\nInput a value: ";
cin >> answer;
operations:
cin >> operation;
if (operation != '=')
if (operation == '+')
cin >> value;
cout << "\n" << answer << " " << operation << " " << value << "\n";
answer += value;
cout << "Equals " << answer << "\n";
cout << answer << " - New Operation? ";
goto operations;
if (operation == '-')
cin >> value;
cout << "\n" << answer << " " << operation << " " << value << "\n";
answer -= value;
cout << "Equals " << answer << "\n";
cout << answer << " - New Operation? ";
goto operations;
if (operation == '*')
cin >> value;
cout << "\n" << answer << " " << operation << " " << value << "\n";
answer *= value;
cout << "Equals " << answer << "\n\n";
cout << answer << " - New Operation? ";
goto operations;
if (operation == '/')
cin >> value;
cout << "\n" << answer << " " << operation << " " << value << "\n";
answer /= value;
cout << "Equals " << answer << "\n\n";
cout << answer << " - New Operation? ";
goto operations;
if (operation == '^')
cin >> value;
cout << "\n" << answer << " " << operation << " " << value << "\n";
answer = pow(answer, value);
cout << "Equals " << answer << "\n\n";
cout << answer << " - New Operation? ";
goto operations;
if (operation == '=')
cout << "\nFinal Answer = " << answer << "\n\nNew operation [yes/no]: ";
string check;
cin >> check;
if (check == "yes")
cout << "\nInput value: ";
cin >> answer;
cout << "\n";
goto operations;
else
cout << "\nGoodbye for now...\n";
return 0;
else
cout << "Unknown Error! Program Closing...";
return 0;
return 0;
当用户使用除 = 之外的任何操作时,它都能正常工作,但如果我使用和等号,它就不起作用了。
示例程序输出:
Welcome to My Calculator
Input a value: 4
+4
4 + 4
Equals 8
8 - New Operation? - 3
8 - 3
Equals 5
5 - New Operation? * 5
5 * 5
Equals 25
25 - New Operation? /2
25 / 2
Equals 12.5
12.5 - New Operation? ^2
12.5 ^ 2
Equals 156.25
156.25 - New Operation? =
Unknown Error! Program Closing...
【问题讨论】:
if (operation != '=') ... if (operation == '=')
这不应该编译,因为这行:operations
。那里没有冒号,而且循环更适合。
@user2371751:对试图帮助修复您的程序的人说“它不起作用”就像去看医生并告诉他“我感觉不好”——仅此而已。
【参考方案1】:
if (operation != '=')
...
if (operation == '=')
如果运算不等于“=”并且等于“=”。我认为您计划在第一个外部 if 中放置一个 闭包运算符 或类似的东西。
【讨论】:
【参考方案2】:您的语句 if (operation != '=')
导致控制权转移到 else 语句
【讨论】:
【参考方案3】:因为您在检查 =
的 if 之外有一个 if (operation != '=')
。你不想那样做。
【讨论】:
以上是关于C++ 常量字符的主要内容,如果未能解决你的问题,请参考以下文章