gpt4 book ai didi

c++ - Python 输入和异常与 C++

转载 作者:行者123 更新时间:2023-11-30 04:18:52 25 4
gpt4 key购买 nike

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

额外:如果您查看最后一个 print 语句中的代码,这是同时打印 var 和 strings 的好方法吗?

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

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);
}

python

class MyError(Exception):   #custom exception class
pass

def hmean(a, b):
if (a == -b):
raise MyError("bad hmean() arguments: a = -b not allowed") #raise similar to throw in C++?
return 2 * a * b / (a + b);

print "Enter two numbers: "

while True:
try:
x, y = raw_input('> ').split() #enter a space between the 2 numbers; this is what .split() allows.
x, y = int(x), int(y) #convert string to int
z = hmean(x, y)
except MyError as error:
print error
print "Enter a new pair of numbers: "
continue

print "Harmonic mean of", x, 'and', y, 'is', z, #is this the most pythonic way using commas?
print "Enter next set of numbers <control + z to quit>: " #force EOF

#print "Bye!" #not getting this far because of EOF

最佳答案

对于函数 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)

最后,如果在将 x 或 y 转换为 int 时出现 ValueError,您可能希望使用 except block 。

关于c++ - Python 输入和异常与 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16137214/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com