calculating expression without using semicolon

淺唱寂寞╮ 提交于 2019-12-12 20:38:40

问题


Given the expression by input like 68+32 we have to evaluate without using a semicolon in our program. If it will be something inside the if or for loop? Reference : https://www.spoj.pl/problems/EXPR2/


回答1:


You can use if and the comma operator, something like this:

if( expr1, expr2, expr3, ... ) {}

It would be equivalent to

expr1;
expr2;
expr3;
...

To use variables without any warnings you can define a function the recieves the data types you need that you call from your main, like so:

void myFunc(int a, double b) {
    if ( expr1, expr2 ) { }
}
int main() {
    if ( myFunc(0, 0), 0 ) { }
}

Note that you need to add , 0 in main, otherwise an error is raised because a void return is not ignored.




回答2:


You can use constructs like this:

if (i++) {}

However, that still doesn't answer how to declare variables. However, one trick you can do is:

#include <iostream>

int main(double x, double y) {
    if ((x = 1)) {}
    if ((y = 2)) {}
    if (std::cout << x << ", " << y << std::endl) {}
}

Sure, you'll get warnings for using the wrong types in the main argument list, but it'll work.



来源:https://stackoverflow.com/questions/1919574/calculating-expression-without-using-semicolon

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!