Swift 100个入门实例程序之00-05
程序员文章站
2024-02-20 19:18:34
...
学习Swift过程所写,题目参考自《100道经典c语言编程题》,如有谬误请指出
0.定义一个包含姓名年龄分数的学生结构体并输出学生名称
struct student{
var name:String
var age:Int
var year:Int
var mark:Int
}
let stu1 = student(name : "John",age : 15,year : 1999,mark : 80)
let stu2 = student(name : "Seelea",age:14,year :2000,mark:99)
let stu3 = student(name : "More",age : 12,year:2002,mark:34)
print(stu1.name)
print(stu2.name)
print(stu3.name)
1.输入一行字符,分别统计出其中字母、空格、数字和其他字符的个数。
let inputstr:String = "hello 123456! all!!!"
var space = 0
var letter = 0
var number = 0
var other = 0
for char in inputstr.characters
{
if char >= "A" && char <= "z"
{
letter += 1
}
else if char >= "0" && char <= "9"
{
number += 1
}
else if char == " "
{
space += 1
}
else
{
other += 1
}
}
print("letter:\(letter) number:\(number) space:\(space) other:\(other)")
2.输入两个正整数,m和n,求其最大公约数
var topic1_m:Int = 30
var topic1_n:Int = 125
var topic1_maxconvent:Int = 0
var topic1_mincommon:Int = 0
var count = 1
topic1_maxconvent = 1
if topic1_m > topic1_n
{
while(count <= topic1_n)
{
if(topic1_m % count == 0 && topic1_n % count == 0)
{
topic1_maxconvent = count
}
count += 1
}
}
else
{
while(count <= topic1_m)
{
if(topic1_m % count == 0 && topic1_n % count == 0)
{
topic1_maxconvent = count
}
count += 1
}
}
print("Input number m: \(topic1_m) \r\nInput number n: \(topic1_n)")
print("Max convent: \(topic1_maxconvent)")
3.输入一个正整数求出它是几位数;输出原数和位数。
var wholenumber = 22325600
var count = 0
print("Origin number: \(wholenumber)")
while(wholenumber > 0)
{
wholenumber /= 10
count += 1
}
print("The integer bits:\(count)")
4.输入一个正整数,输出原数并逆序打印出各位数字。
var wholenumber = 22325600
var count = 0
print("Origin number: \(wholenumber)")
while(wholenumber > 0)
{
print(wholenumber%10)
wholenumber /= 10
}
上一篇: set数据结构
下一篇: 数据结构之Map和Set