我是第一个计算机科学课的学生。我试图找出如何设置变量,以便它需要一个数字附加到我们的老师设置的命令./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)
答案 0 :(得分:1)
使用Int(String)
将参数解析为整数。请注意,如果字符串不是整数,它将返回nil Int?
,您应该处理这种情况。
guard let number = Int(firstParameter) else {
fatalError("firstParameter is not an Int")
}
编辑:您还应该检查参数是否存在,否则CommandLine.arguments[1]
将失败,索引超出范围。