Python输入和异常与C++; 我想复制下面的C++代码,输入和异常处理尽可能接近于Python方式。我取得了成功,但可能不是我想要的。我希望退出类似于C++输入随机字符的程序,在这种情况下,它是一个“q”。while条件中的cin对象不同于python使while为True的方式。我还想知道把2个输入转换成int的简单方法是否合适。最后,在python代码中,“再见!”永远不会运行,因为EOF(control+z)方法强制关闭应用程序。有一些怪癖,总的来说,我对python所需的代码更少感到满意

Python输入和异常与C++; 我想复制下面的C++代码,输入和异常处理尽可能接近于Python方式。我取得了成功,但可能不是我想要的。我希望退出类似于C++输入随机字符的程序,在这种情况下,它是一个“q”。while条件中的cin对象不同于python使while为True的方式。我还想知道把2个输入转换成int的简单方法是否合适。最后,在python代码中,“再见!”永远不会运行,因为EOF(control+z)方法强制关闭应用程序。有一些怪癖,总的来说,我对python所需的代码更少感到满意,c++,python,input,exception-handling,C++,Python,Input,Exception Handling,额外:如果您查看上一个print语句中的代码,这是将var和字符串一起打印的好方法吗 欢迎使用任何简单的技巧/提示 C++ #include <iostream> using namespace std; double hmean(double a, double b); //the harmonic mean of 2 numbers is defined as the invese of the average of the inverses. int main() {

额外:如果您查看上一个print语句中的代码,这是将var和字符串一起打印的好方法吗

欢迎使用任何简单的技巧/提示

C++

#include <iostream>

using namespace std;

double hmean(double a, double b);  //the harmonic mean of 2 numbers is defined as the invese of the average of the inverses.

int main()
{
    double x, y, z;
    cout << "Enter two numbers: ";

    while (cin >> x >> y)
    {
        try     //start of try block
        {
            z = hmean(x, y);
        }           //end of try block
        catch (const char * s)      //start of exception handler; char * s means that this handler matches a thrown exception that is a string
        {
            cout << s << endl;
            cout << "Enter a new pair of numbers: ";
            continue;       //skips the next statements in this while loop and asks for input again; jumps back to beginning again
        }                                       //end of handler
        cout << "Harmonic mean of " << x << " and " << y
            << " is " << z << endl;
        cout << "Enter next set of numbers <q to quit>: ";
    }
    cout << "Bye!\n";

    system("PAUSE");
    return 0;
}

double hmean(double a, double b)
{
    if (a == -b)
        throw "bad hmean() arguments: a = -b not allowed";
    return 2.0 * a * b / (a + b);
}
#包括
使用名称空间std;
双H平均值(双a,双b)//2个数的调和平均数定义为倒数平均数的倒数。
int main()
{
双x,y,z;
cout>x>>y)
{
try//try块的开始
{
z=hmean(x,y);
}//try块结束
catch(const char*s)//异常处理程序的开始;char*s表示此处理程序匹配作为字符串的抛出异常
{

cout对于函数
hmean
我将尝试执行return语句,如果
a
等于
-b
,则引发异常:

def hmean(a, b):
    try:
        return 2 * a * b / (a + b)
    except ZeroDivisionError:
        raise MyError, "bad hmean() arguments: a = -b not allowed"
要在字符串中插入变量,方法
format
是一种常见的替代方法:

print "Harmonic mean of {} and {} is {}".format(x, y, z)

最后,如果 > ValueError 在x或y被转换为<代码> int >代码>时,你可能想使用<代码>,

这是一个我想向你扔的代码。类似的东西在C++中不太可能,但是通过分离关注点,它使得Python中的东西变得更加清晰:

# so-called "generator" function
def read_two_numbers():
    """parse lines of user input into pairs of two numbers"""
    try:
        l = raw_input()
        x, y = l.split()
        yield float(x), float(y)
    except Exception:
        pass

for x, y in read_two_numbers():
    print('input = {}, {}'.format(x, y))
print('done.')
它使用了一个所谓的generator函数,只处理输入解析以将输入与计算分离。这不是“尽可能接近”,而是您要求的“以pythonic方式”,但我希望您会发现这很有用。此外,我还冒昧地使用float而不是int来表示数字


还有一件事:升级到Python3,版本2不再开发,只会收到错误修复。如果您不依赖任何仅适用于Python2的库,您应该不会觉得有太大的区别。

raise与throw是等价的吗在C++中?谢谢其他方法。注意。@ KLUNHOME是的,我也建议你看一下处理击键事件。有类似C++的方式,在哪里“Q”?虽然它可能涉及更多的工作,但另一个例外。我喜欢C++中的CIN对象。键入“Q”会导致两个数字的提取失败,从而终止<代码>(CIN)。在Python中,你读一行然后解析它。解析代码会在失败时引发异常,所以有等价的。换句话说,除了块之外,你需要两个尝试,一个处理非数值输入或EOF的外部操作,一个内部处理无效的输入值。BTW:在C++中,通常抛出P不是一个好主意。lain指针。相反,你应该使用
std::runtime_error
,它还可以携带字符串作为上下文信息。这是深入的。感谢你的努力,因为我将研究你的代码。我现在有点倾向于使用python 2.7,因为它对Django框架有最好的支持。如果我错了,请纠正我。浮点的使用非常简单注意。
# so-called "generator" function
def read_two_numbers():
    """parse lines of user input into pairs of two numbers"""
    try:
        l = raw_input()
        x, y = l.split()
        yield float(x), float(y)
    except Exception:
        pass

for x, y in read_two_numbers():
    print('input = {}, {}'.format(x, y))
print('done.')