我试图计算两个随机数的最大公共分频器,这是我的源代码。引用表明:
TypeError: not all arguments converted during string formatting
但实际上,我不打算进行任何字符串格式化。我该如何纠正?
def gcd(Num_1, Num_2):
c = (Num_1 % Num_2);
Num_1 = Num_2;
Num_2 = c;
if c != 0:
return gcd(Num_1, Num_2)
else:
return Num_1
Num_1 = raw_input("a\n>");
Num_2 = raw_input("b\n>");
gcd(Num_1, Num_2);
答案 0 :(得分:1)
使用raw_input()
获取输入时,会返回字符串,因此Num_1
和Num_2
是字符串,而不是int,因此当您在其上使用%
时,Python假设它是字符串格式化运算符,而不是模块运算符,并且由于左侧没有格式,因此会出现错误。示例 -
>>> '1' % '2'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting
您应该按照预期int
将输入转换为int
。此外,还有一种更简单的方法可以在Python中交换元素(你试图用临时变量做什么) -
def gcd(Num_1, Num_2):
Num_1, Num_2 = Num_2, (Num_1 % Num_2)
if c != 0:
return gcd(Num_1, Num_2)
else:
return Num_1
Num_1 = int(raw_input("a\n>"))
Num_2 = int(raw_input("b\n>"))
gcd(Num_1, Num_2)
答案 1 :(得分:0)
@model IdentitySample.Models.RegisterViewModel
@using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
<h4>Create a new account.</h4>
<hr />
@Html.ValidationSummary("", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.PasswordFor(m => m.Password, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.ConfirmPassword, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Register" />
</div>
</div>
}
返回一个字符串,字符串上的%表示字符串格式。
请尝试使用raw_input
:https://docs.python.org/2.7/library/functions.html?highlight=input#input