我的作业中有一个很奇怪的问题。所以我必须构建一个计算两个数字的和/差的函数。
这看起来相当简单,但有一个问题。
这是函数:
void sumdif()
{
int result = 0;
//input
//output
}
Run Code Online (Sandbox Code Playgroud)
我不能使用任何分号,这就是函数的外观。
输入包含:数字、+ 或 -(取决于您要减去还是添加)和另一个数字。
该函数将输出结果。
如果我可以使用分号,那就很容易了。不过,我不知道在这种情况下如何解决这个问题。
我考虑过使用三元运算符。不幸的是,我不知道如何在一行中获取输入、输出以及区分 + 和 - 。(我想我无论如何都需要“;”,所以它对我没有帮助)。
这是问题: https://www.pbinfo.ro/?pagina =probleme&id=3191
不幸的是,它是罗马尼亚语的。您可以使用谷歌翻译了解更多详细信息,但我已经解释了这个想法。
通过该函数,您可以获取输入,然后输出结果,除此之外,您不能使用任何分号。(这对我来说是最难的部分 - 我以前从未处理过这个)
如何解决这个问题呢?
只需执行条件内的操作,if如下所示:
void sumdif()
{
if (char c = '+') { //declare c
if (cin >> c) { //read c
if (int a = 1) { //declare a
if (cin >> a) { //read a
if (int b = 1) { //declare b
if (cin >> b) { //read b
if (c == '+') { //choose operation
if (cout << (a + b)) { //print sum
}
}
else {
if (cout << (a - b)) { //print difference
}
}
}
}
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)