小编Nao*_*son的帖子

Python 3 中的 int() 与 float() 输入及其实用程序?

这并不是指我的特定代码,因此我希望这不会违反提出问题的社区标准。我还在学习中,所以如果这类问题不合适,请告诉我,以供以后参考!

当我开始学习使用 Python 3 时,我试图彻底了解某些命令的实用性。我以前从未编码过,所以我没有任何其他语言的背景。我希望有人能帮助我更彻底地理解这一点。

基本上,我明白,当提示用户输入数值时,有时写正确float(input()),有时写正确int(input())。我在数学中知道整数是整数,浮点数是用整数部分、基数和尾数定义的任何数字(例如 4.32)。我不明白将用户输入转换为其中一种的效用。

例如,如果我编写int(input("Input a decimal. "))并且用户输入4.3,程序将返回值错误。这有什么用处呢?所以:

  1. input()将 an 转换为float()or有什么用处int()
  2. 我知道何时需要一个整数(例如,如果我希望用户输入将特定数字与其自身相乘的次数),但为什么我需要浮点输入?
  3. 一般来说,我什么时候需要实现其中之一,以及如何识别程序需要哪一个?
  4. 除了用户输入之外,在其他什么情况下我还想实现任一命令?
  5. 如果有人对如何以及何时转换某些定义的变量或输入有任何其他阅读,请发送给我!

编辑:

这是我编写的代码示例,我认为它突出了我对是否以及何时使用int()and的困惑float()

price=input("How much did the item cost?: $")
if float(price)<0:
    print("The price cannot be negative.")
else:
    price=int(float(price)*100)
    paid=input("How much did the customer pay?: $")
    paid=int(float(paid)*100)
Run Code Online (Sandbox Code Playgroud)

我这样做正确吗?这是其中一部分的较大程序工作正常,但我不确定是否添加了不必要的命令或正确实现了命令。

非常感谢你的帮助!

内奥米

python floating-point int python-3.x

4
推荐指数
1
解决办法
2万
查看次数

只返回第一个if语句?(C++)

这是我正在进行的任务:

编写一个程序,提示用户输入课程所获得的分数并确定分数.该程序应显示成绩的成绩和消息字符串.使用'if else'语句确定要打印消息字符串的等级和switch语句.

我编写了代码并且执行时没有任何调试错误.问题是,无论我输入什么作为我PointsEarned,我只得到F的输出!例如,如果我输入"90":

Try Harder Next Time.
GRADE: F
Run Code Online (Sandbox Code Playgroud)

有什么问题?我把我的switch语句放在错误的地方吗?这是代码:

#include <iostream>
using namespace std;
int main()
{
    int PointsEarned;
    char Grade;
    cout << "Please input the points earned in the course: ";
    cin >> PointsEarned;
    if (0 <= PointsEarned < 60) {
        Grade = 'F';
    }
    else if (60 <= PointsEarned < 70) {
        Grade = 'D';
    }
    else if (70 <= PointsEarned < 80) {
        Grade = 'C';
    }
    else if (80 <= PointsEarned < …
Run Code Online (Sandbox Code Playgroud)

c++ if-statement switch-statement

0
推荐指数
1
解决办法
104
查看次数