简体   繁体   English

在不使用任何分号的情况下编写 function

[英]Write a function without using any semicolon

I have a very strange problem in my homework.我的作业中有一个非常奇怪的问题。 So I have to build a function which calculates the sum/difference of two numbers.所以我必须构建一个 function 来计算两个数字的和/差。

It looks fairly easy but there's a catch.它看起来相当容易,但有一个问题。

This is the function:这是 function:

void sumdif()
{
int result = 0;
//input
//output
}

I can't use any semicolons, and this is how the function must look.我不能使用任何分号,这就是 function 的外观。

Input consists of: number, + or - (depending if you want to substract or to add) and another number.输入包括:数字、+ 或 -(取决于您是要减法还是加法)和另一个数字。

The function will output the result. function 将 output 结果。

If I could use semi-colons, it would've been easy.如果我可以使用分号,那就很容易了。 I have no idea how to resolve this problem in this case, though.不过,我不知道在这种情况下如何解决这个问题。

I've thought about using a ternary operator.我考虑过使用三元运算符。 Unfortunately, I can't see how to take input, output and also differentiate + and - in one line.不幸的是,我看不到如何输入 output 并且还区分 + 和 - 在一行中。 (and I think I needed ";" anyway so it wouldn't help me). (而且我认为我需要“;”无论如何它对我没有帮助)。

Here's the problem: https://www.pbinfo.ro/?pagina=probleme&id=3191这是问题所在: https://www.pbinfo.ro/?pagina=probleme&id=3191

Unfortunately, it is in romanian.不幸的是,它是罗马尼亚语的。 You can use google translate for more details, but I've explained the idea.您可以使用谷歌翻译了解更多详细信息,但我已经解释了这个想法。

Through that function you take input, then output the result, and more than that you can't use any semicolon.通过 function 输入,然后 output 结果,除此之外,您不能使用任何分号。 (this is the hardest part for me - I've never dealt with this before) (这对我来说是最难的部分——我以前从未处理过这个)

How can this problem be solved?如何解决这个问题?

Just performs the operations inside the if condition like in the following:只需执行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
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

LIVE DEMO现场演示

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

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