gpt4 book ai didi

swift - 协助 Swift 中的变量

转载 作者:行者123 更新时间:2023-11-28 06:05:00 28 4
gpt4 key购买 nike

我是第一个计算机科学类的学生。我想弄清楚如何设置变量,以便它接受一个数字,该数字附加到我们老师设置的命令 ./integerProperties 。请查看我编写的代码,我可以使用一些帮助来了解如何获取该输入并将其插入我名为 number 的变量中。

27 │Example output for:  ./integerProperties 1983
28 │
29 │ The number is even:
30 │ false
31 │ The number is odd:
32 │ true
33 │ The number is evenly divisible by three:
34 │ true
35 │ The number is evenly divisible by five:
36 │ false
37 │ The number is evenly divisible by seven:
38 │ false
39 │ How many groups of ten?
40 │ 198
41 │ How many groups of hundred?
42 │ 19
43 │ The additive inverse:
44 │ -1983
45 │
46 │
47 │
48 │ */
49 │ let firstParameter = CommandLine.arguments[1]
50 │ var number: Int
51 │
52 │ print("The number is even:")
53 │ print(number % 2 == 0)
54 │ print("The number is odd ")
55 │ print(number % 2 != 0)
56 │ print("the number is evenly divisible by 3")
57 │ print(number % 3 == 0)
58 │ print("the number is evenly divisible by 5")
59 │ print(number % 5 == 0)
60 │ print("the number of evenly divisible by 7")
61 │ print(number % 7 == 0)
62 │ print("how many groups of ten")
63 │ print(number / 10)
64 │ print("how many groups of hundreds")
65 │ print(number / 100)
66 │ print("the additive inverse")
67 │ print(number * -1)

最佳答案

使用 Int(String) 将参数解析为整数。请注意,如果字符串不是整数,它将返回 nil Int?,您应该处理这种情况。

guard let number = Int(firstParameter) else {
fatalError("firstParameter is not an Int")
}

编辑:您还应该检查参数是否存在,否则 CommandLine.arguments[1] 将因索引超出范围而失败。

关于swift - 协助 Swift 中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48493001/

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