C++ if语句';条件
在这本书第三章的练习十中,我试着复习一下,我被要求写一个程序,它接受一个后跟两个操作数的运算并输出结果。 将操作读入一个名为operations的字符串,并使用if语句找出用户想要的操作。将操作数读入double类型的变量。对于名为+、-、*、/(加号、减号、乘法、除法)的操作,可以实现这一点 这就是我到目前为止所写的,它是有效的,除了我的问题外,所有的问题都是if语句中的条件概念。据我所知,if语句中有括号,在这些条件中,只有在计算机决定是否运行代码之后,才会测试值以确定它们是否为真。那么,告诉我为什么我必须写等于运算符的运算作为条件,而我必须在cout中使用运算符来获得两个输入值的结果?我不明白这一点,难道没有更好的方法用更少的语句来写这篇文章吗C++ if语句';条件,c++,if-statement,C++,If Statement,在这本书第三章的练习十中,我试着复习一下,我被要求写一个程序,它接受一个后跟两个操作数的运算并输出结果。 将操作读入一个名为operations的字符串,并使用if语句找出用户想要的操作。将操作数读入double类型的变量。对于名为+、-、*、/(加号、减号、乘法、除法)的操作,可以实现这一点 这就是我到目前为止所写的,它是有效的,除了我的问题外,所有的问题都是if语句中的条件概念。据我所知,if语句中有括号,在这些条件中,只有在计算机决定是否运行代码之后,才会测试值以确定它们是否为真。那么,告
#include "stdafx.h"
#include "iostream"
#include "string"
using namespace std;
int main()
{
string operation = "";
double operands1;
double operands2;
cout << "Give me either a minus, plus, division, or multiplication operations \n";
cin >> operation;
cout << " enter the value you would like to \n";
cin >> operands1;
cout << " enter the second value you would like to \n";
cin >> operands2;
if (operation == "+")// I was told to write it like this in the book {
cout << operands1 + operands2 << endl;
}
else if (operation == "*") {
cout << operands1*operands2 << endl;
}
else if (operation == "-") {
cout << operands1 - operands2 << endl;
}
else if (operation == "/") {
cout << operands1 / operands2 << endl;
}
else {
cout << " seriously dude im talking about numbers over here \n";
}
return 0;
}
#包括“stdafx.h”
#包括“iostream”
#包括“字符串”
使用名称空间std;
int main()
{
字符串操作=”;
双操作数1;
双操作数2;
cout>操作;
cout>操作数1;
cout>2;
if(operation==“+”)//我被告知在书中这样写{
cout对于单字符操作,可以使用switch语句:
switch (c) {
case '+' : std::cout << op1 + op2 << std::endl; break;
case '*' : ...
...
default : std::cout << "my dud!" << std::endl;
}
开关(c){
案例“+”:std::cout如果你在问为什么不能这样做:
cout << operands1 operation operands2 << endl;
cout赋值有些混乱,因为运算符“+”实际上是一个字符串
if (operation == "+")// I was told to write it like this in the book {
cout << operands1 + operands2 << endl;
}
if(operation==“+”)//我被告知在书中这样写{
“如果我有更多的时间,我会写一封更短的信”——马克·吐维尼得出了同样的结论,这就是他们所问的。我考虑过用std::map
写一个有趣的答案,但我决定不这样做。
if (operation == "+")// I was told to write it like this in the book {
cout << operands1 + operands2 << endl;
}