基础30题
练习 1:有两个变量,a 和 b,要求将其进行交换,最终打印结果
a := 9
b := 2
t := a
a = b //
b = t //
fmt.Printf("交换后的情况是 a = %v )
练习 2:假如还有 100 天放假,问:xx 个星期零 xx 天
package main
import "fmt"
fun main (){
days := 100
week := 100 / 7
day := 100 % 7
fmt.printf("%d个星期零%d天",week,day)
}
练习 3:定义一个变量保存华氏温度,华氏温度转换摄氏温度的公式为:5/9*(华氏温度-100), 请求出华氏温度对应的摄氏温度
var huashi float32 = 134.2
var sheshi float32 = 5.0 / 9 * (huashi - 100)
fmt.Printf("%v 对应的摄氏温度=%v \n", huashi, sheshi)
练习 4:请求一个数组里面元素的和以及这些元素的平均值,分别用for和for-range实现
var arr = [...]int{12,23,33,44,555,666}
sum := 0
for i:=0;i<len(arr);i++{
sum += arr[i]
}
fmt.printf("arr数组元素和是%v,平均值:%.2f",sum,float64(sum)/float64(len(arr)))
练习5:请求出一个数组的最大值,并得到对应的下标
var index int
arr := [...]int{1,-1,12,65,11}
max := arr[0]
for i:=0;i<len(arr);i++{
if max <arr[i]{
max = arr[i]
index = i
}
}
fmt.Printf("最大值:%v 最大值对应的索引值:%v",max,index)
练习6:从数组[1,3,5,7,8]中找出和为8的两个 元素的下标分别为(0,3)和(1,2)
arr :=[...]int{1,3,5,7,8}
for i :=0;i<len(arr);i++{
for j :=i+1;j<len(arr);j++{
if arr[i]+arr[j]==8{
fmt.Printf("%v,%v",i,j)
}
}
}
练习7:统计“ 我有一个梦想”英文文章中每个英文字母(不区分大小写字母)(不统计标点符号)出现的次数
package main
import "fmt"
func main() {
//字符串
article := ` I am happy to join with you today in what will go down in history as the greatest demonstration for freedom in the history of our nation.
Five score years ago, a great American, in whose symbolic shadow we stand today, signed the Emancipation Proclamation. This momentous decree came as a great beacon light of hope to millions of Negro slaves who had been seared in the flames of withering injustice. It came as a joyous daybreak to end the long night of bad captivity.
But one hundred years later, the Negro still is not free. One hundred years later, the life of the Negro is still sadly crippled by the manacles of segregation and the chains of discrimination. One hundred years later, the Negro lives on a lonely island of poverty in the midst of a vast ocean of material prosperity. One hundred years later, the Negro is still languished in the corners of American society and finds himself an exile in his own land. And so we've come here today to dramatize a shameful condition.
In a sense we've come to our nation's capital to cash a check. When the architects of our republic wrote the magnificent words of the Constitution and the Declaration of Independence, they were signing a promissory note to which every American was to fall heir. This note was a promise that all men, yes, black men as well as white men, would be guaranteed the "unalienable Rights" of "Life, Liberty and the pursuit of Happiness." It is obvious today that America has defaulted on this promissory note, insofar as her citizens of color are concerned. Instead of honoring this sacred obligation, America has given the Negro people a bad check, a check which has come back marked "insufficient funds."
But we refuse to believe that the bank of justice is bankrupt. We refuse to believe that there are insufficient funds in the great vaults of opportunity of this nation. And so, we've come to cash this check, a check that will give us upon demand the riches of freedom and the security of justice.
We have also come to this hallowed spot to remind America of the fierce urgency of Now. This is no time to engage in the luxury of cooling off or to take the tranquilizing drug of gradualism. Now is the time to make real the promises of democracy. Now is the time to rise from the dark and desolate valley of segregation to the sunlit path of racial justice. Now is the time to lift our nation from the quicksands of racial injustice to the solid rock of brotherhood. Now is the time to make justice a reality for all of God's children.
It would be fatal for the nation to overlook the urgency of the moment. This sweltering summer of the Negro's legitimate discontent will not pass until there is an invigorating autumn of freedom and equality. Nineteen sixty-three is not an end, but a beginning. And those who hope that the Negro needed to blow off steam and will now be content will have a rude awakening if the nation returns to business as usual. And there will be neither rest nor tranquility in America until the Negro is granted his citizenship rights. The whirlwinds of revolt will continue to shake the foundations of our nation until the bright day of justice emerges.
But there is something that I must say to my people, who stand on the warm threshold which leads into the palace of justice: In the process of gaining our rightful place, we must not be guilty of wrongful deeds. Let us not seek to satisfy our thirst for freedom by drinking from the cup of bitterness and hatred. We must forever conduct our struggle on the high plane of dignity and discipline. We must not allow our creative protest to degenerate into physical violence. Again and again, we must rise to the majestic heights of meeting physical force with soul force.
The marvelous new militancy which has engulfed the Negro community must not lead us to a distrust of all white people, for many of our white brothers, as evidenced by their presence here today, have come to realize that their destiny is tied up with our destiny. And they have come to realize that their freedom is inextricably bound to our freedom.
We cannot walk alone.
And as we walk, we must make the pledge that we shall always march ahead.
We cannot turn back.
There are those who are asking the devotees of civil rights, "When will you be satisfied?" We can never be satisfied as long as the Negro is the victim of the unspeakable horrors of police brutality. We can never be satisfied as long as our bodies, heavy with the fatigue of travel, cannot gain lodging in the motels of the highways and the hotels of the cities. We cannot be satisfied as long as the Negro's basic mobility is from a smaller ghetto to a larger one. We can never be satisfied as long as our children are stripped of their selfhood and robbed of their dignity by signs stating "for whites only." We cannot be satisfied as long as a Negro in Mississippi cannot vote and a Negro in New York believes he has nothing for which to vote. No, no, we are not satisfied, and we will not be satisfied until "justice rolls down like waters, and righteousness like a mighty stream."
I am not unmindful that some of you have come here out of great trials and tribulations. Some of you have come fresh from narrow jail cells. And some of you have come from areas where your quest -- quest for freedom left you battered by the storms of persecution and staggered by the winds of police brutality. You have been the veterans of creative suffering. Continue to work with the faith that unearned suffering is redemptive. Go back to Mississippi, go back to Alabama, go back to South Carolina, go back to Georgia, go back to Louisiana, go back to the slums and ghettos of our northern cities, knowing that somehow this situation can and will be changed.
Let us not wallow in the valley of despair, I say to you today, my friends.
And so even though we face the difficulties of today and tomorrow, I still have a dream. It is a dream deeply rooted in the American dream.
I have a dream that one day this nation will rise up and live out the true meaning of its creed: "We hold these truths to be self-evident, that all man are created equal."
I have a dream that one day on the red hills of Georgia, the sons of former slaves and the sons of former slave owners will be able to sit down together at the table of brotherhood.
I have a dream that one day even the state of Mississippi, a state sweltering with the heat of injustice, sweltering with the heat of oppression, will be transformed into an oasis of freedom and justice.
I have a dream that my four little children will one day live in a nation where they will not be judged by the color of their skin but by the content of their character.
I have a dream today!
I have a dream that one day, down in Alabama, with its vicious racists, with its governor having his lips dripping with the words of "interposition" and "nullification" -- one day right there in Alabama little black boys and black girls will be able to join hands with little white boys and white girls as sisters and brothers.
I have a dream today!
I have a dream that one day every valley shall be exalted, and every hill and mountain shall be made low, the rough places will be made plain, and the crooked places will be made straight; "and the glory of the Lord shall be revealed and all flesh shall see it together."
This is our hope, and this is the faith that I go back to the South with.
With this faith, we will be able to hew out of the mountain of despair a stone of hope. With this faith, we will be able to transform the jangling discords of our nation into a beautiful symphony of brotherhood. With this faith, we will be able to work together, to pray together, to struggle together, to go to jail together, to stand up for freedom together, knowing that we will be free one day.
And this will be the day -- this will be the day when all of God's children will be able to sing with new meaning:
My country 'tis of thee, sweet land of liberty, of thee I sing.
Land where my fathers died, land of the Pilgrim's pride,
From every mountainside, let freedom ring!
And if America is to be a great nation, this must become true.
And so let freedom ring from the prodigious hilltops of New Hampshire.
Let freedom ring from the mighty mountains of New York.
Let freedom ring from the heightening Alleghenies of
Pennsylvania.
Let freedom ring from the snow-capped Rockies of Colorado.
Let freedom ring from the curvaceous slopes of California.
But not only that:
Let freedom ring from Stone Mountain of Georgia.
Let freedom ring from Lookout Mountain of Tennessee.
Let freedom ring from every hill and molehill of Mississippi.
From every mountainside, let freedom ring.
And when this happens, when we allow freedom ring, when we let it ring from every village and every hamlet, from every state and every city, we will be able to speed up that day when all of God's children, black men and white men, Jews and Gentiles, Protestants and Catholics, will be able to join hands and sing in the words of the old Negro spiritual:
Free at last! Free at last!
Thank God Almighty, we are free at last!`
// 遍历英文字母, for range
// 过滤掉非英文字符(byte/rune)整数
// xxx a--z XXXX A--Z
// 'a' <= xx <='z' || 'A'<=XX<='Z'
stat := map[rune]int{}
for _, ch := range article {
if ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' {
stat[ch]++ // stat[ch] = stat[ch]+1
}
}
for ch, v := range stat {
fmt.Printf("%c: %d\n", ch, v)
}
}
//附加题:通过map的value实现对map的排序
type count struct {
key rune
val int
}
tmplist := make([]count, 0)
for ch, v := range stat {
tmplist = append(tmplist, count{key: ch, val: v})
}
sort.Slice(tmplist, func(i, j int) bool {
return tmplist[i].val > tmplist[j].val
})
for _, pair := range tmplist {
fmt.Printf("key:%c,val:%v\n", pair.key, pair.val)
}
练习8:int切片[] int{108,107,105,109,103,102} 找出最大的数字
方法一:
numl := []int{108, 107, 105, 109, 103, 102}
sort.Ints(numl)
fmt.Println(numl[len(numl)-1])
方法二:
num := []int{108, 107, 110, 120, 133, 144}
max := num[0]
for i := 0; i < len(num); i++ {
if max < num[i] {
max = num[i]
}
}
fmt.Println(max)
练习9:针对问题8的切片,将最大的数字移动到切片的最后一位 原来的数字都再移动后的切片中都存在,只是最大的数字再最后一位
num := []int{108, 107, 105, 109, 103, 102}
for i := 0; i < len(num)-1; i++ {
if num[i] > num[i+1] {
num[i], num[i+1] = num[i+1], num[i]
}
}
fmt.Println(num)
练习10:针对问题9.将第二大的移动到切片的最后第二位
for j := 0; j < 2; j++ {
for i := 0; i < len(num)-1; i++ {
if num[i] > num[i+1] {
num[i], num[i+1] = num[i+1], num[i]
}
}
}
练习11:使用冒泡排序对问题8切片进行从小到答排序
for i := 0; i < len(num); i++ {
for j := 0; j < len(num)-1; j++ {
if num[j] > num[j+1] {
num[j], num[j+1] = num[j+1], num[j]
}
}
}
练习12:选择排序
选择排序:进行从小到大排序
概念: 通过比较 首先选出最小的数放在第一个位置上,然后在其余的数中选出次小数放在第二个位置上,依此类推,直到所有的数成为有序序列。
[9, 8, 7, 6, 5, 4]
//从大到小的排序
var numSlice = []int{6, 5, 4, 9, 8, 7}
for i := 0; i < len(numSlice); i++ {
for j := i + 1; j < len(numSlice); j++ {
if numSlice[i] < numSlice[j] {
temp := numSlice[i]
numSlice[i] = numSlice[j]
numSlice[j] = temp
}
}
}
fmt.Println(numSlice)
练习13:写一个程序、统计一个字符串中每个单词出现的次数
练习14:统计字符串中的单词个数
package main
import (
"fmt"
"strings"
)
func main(){
// 写一个程序,统计一个字符串中每个单词出现的次数。比如:”how do you do”中how=1 do=2 you=1。
words := "how do you do"
// 转为切片类型
wordsSlice := strings.Split(words," ")
// 初始化一个map统计每个单词的数量
wordMap := make(map[string]int)
// 遍历切片中的单词
for _,word := range wordsSlice{
// 判断单词是否在map中作为键
_, ok := wordMap[word]
// 如果作为键,将value的值加1
if ok{
wordMap[word] += 1
// 如果不在,则把单词作为键存储
}else{
wordMap[word] = 1
}
}
fmt.Println(wordMap)
}
方法二
words := "how do you do"
wordSlice := strings.Split(words, " ")
wordmap := make(map[string]int)
for _, word := range wordSlice {
wordmap[word]++
}
fmt.Println(wordmap)
练习15:练习:求 1+2+3+4 +…100 的和
sum := 0
for i := 0; i <= 100; i++ {
sum += i
}
fmt.Println(sum)
练习16:计算 5 的阶乘 (12345 n 的阶乘 12……n)
sum := 1
for i := 1; i <= 5; i++ {
sum *= i
}
练习17:打印 0-50 所有的偶
for i := 1; i <= 50; i++ {
if i%2 == 0 {
fmt.Println(i)
}
}
练习18:打印 1~100 之间所有是 9 的倍数的整数的个数及总和
count := 0
sum := 0
for i := 1; i < 100; i++ {
if i%9 == 0 {
sum += i
count++
}
}
fmt.Println("count=",count)
fmt.Println("sum=",sum)
练习19:打印一个矩形
for i := 1; i <= 12; i++ {
fmt.Print("*")
if i%4 == 0 {
fmt.Println()
}
}
练习20: 打印一个三角形
line := 5
for i := 1; i <= line; i++ {
for j := 0; j < i; j++ {
fmt.Print("*")
}
fmt.Println()
}
练习21:打印出九九乘法表
for i := 1; i <= 9; i++ {
for j := 1; j <= i; j++ {
fmt.Printf("%v*%v=%v\t", i, j, j*i)
}
fmt.Println()
}
练习22:判断文件类型,如果后缀名是.html 输入 text/html, 如果后缀名.css 输出 text/css ,如果 后缀名是.js 输出 text/javascrip
extname := "a"
switch extname {
case ".html":
fmt.Println("text/html")
case ".css":
fmt.Println("text/css")
case ".js":
fmt.Println("text/javascript")
default:
fmt.Println("格式错误")
练习23:猜数字 生成随机数字0-100从控制台数据与生成数字比较 大 提示太大了 小 提示太小了 等于 成功 程序结束 最多猜测五次,未猜对,说太笨了,程序结束
方法一:
num1 := rand.Intn(100)
var count int
for i := 1; i <= 5; i++ {
fmt.Println("请输入你要猜的数字")
fmt.Scan(&count)
if count == num1 {
fmt.Println("成功")
return
} else if count > num1 {
fmt.Println("太大了")
} else if count < num1 {
fmt.Println("太小了")
}
}
fmt.Println("未猜对,说太笨了,程序结束")
方法二:
var count int
num1 := rand.Intn(100)
for i := 1; i <= 5; i++ {
fmt.Println("请输入你要猜的数字")
fmt.Scan(&count)
switch {
case count > num1:
fmt.Println("太大了")
case count == num1:
fmt.Println("成功")
return
case count < num1:
fmt.Println("太小了")
default:
fmt.Println("未猜对,说太笨了,程序结束")
}
}
方法三:
r := rand.New(rand.NewSource(time.Now().UnixNano()))
num1 := r.Intn(100)
var num2 int
count := 0
for true {
if count == 5 {
break
}
fmt.Println("请输入你想要猜的数子")
fmt.Scan(&num2)
if num2 > num1 {
fmt.Println("太大了")
} else if num2 < num1 {
fmt.Println("太小了")
} else if num2 == num1 {
fmt.Println("猜对了")
}
count++
}
fmt.Println("你是笨蛋吗?")
练习23:写一程序求y值(x值由键盘输入),y = (sinx+cosx)/2, x>=0 , y = (sinx-cosx)/2, x<0
package main
import(
"fmt"
"math"
)
func main() {
var x, y float64
fmt.Scan(&x)
if x >= 0 {
y = (math.Sin(x) + math.Cos(x)) / 2.0
} else {
y = (math.Sin(x) - math.Cos(x)) / 2.0
}
fmt.Println(y)
}
练习24:输入一个字符,判断它如果是小写字母输出其对应的大写字母;如果是大写字母输出其对应的小写字母;如果是数字输出数字本身;如果是空格输出“SPACE”;如果不是上述情况输出“Other”
package main
import (
"fmt"
)
func main() {
var ch rune
fmt.Scanf("%c", &ch)
switch {
case (ch >= 'a') && (ch <= 'z'):
fmt.Printf("%c\n", ch-32)
case (ch >= 'A') && (ch <= 'Z'):
fmt.Printf("%c\n", ch+32)
case (ch == ' '):
fmt.Println("SPACE")
case (ch >= '1') && (ch <= '9'):
fmt.Printf("%c\n", ch)
default:
fmt.Println("Other")
}
}
练习25:有三个数a、b、c,由键盘输入,输出其中最大的数。
package main
import (
"fmt"
)
func main() {
var a, b,c int
fmt.Scan(&a,&b,&c)
var max = a
if max < b {
max =b
}
if max < c {
max =c
}
fmt.Println("max=",max)
}
练习26:输入一个数,判断它能否被3或者5整除,如至少能被这两个数中的一个整除则将此数打印出来,否则不打印,编出程序
package main
import (
"fmt"
)
func main() {
var n int
fmt.Scan(&n)
if (n%3 == 0) || (n%5 == 0) {
fmt.Println(n)
}
}
练习27:读入1-7之间的某个数,输出表示一星期中相应的某一天的单词:Monday、Tuesday等,使用switch语句实现
package main
import (
"fmt"
)
func main() {
var n int
fmt.Scan(&n)
switch n {
case 1:
fmt.Println("Monday")
case 2:
fmt.Println("Tuesday")
case 3:
fmt.Println("Wednesday")
case 4:
fmt.Println("Thursday")
case 5:
fmt.Println("Friday")
case 6:
fmt.Println("Saturday")
case 7:
fmt.Println("Sunday")
}
}
练习28:循环打印输入的月份的天数,要有判断输入的月份是否错误的语句。[使用continue实现]
package main
import (
"fmt"
)
func test() {
//定义一个变量用于输入的月份
var month int
var year int
for {
fmt.Println("请输入年份")
fmt.Scanln(&year)
fmt.Println("请输入月份")
fmt.Scanln(&month)
if month != 0 {
switch month {
case 1,3,5,7,8,10,12:
fmt.Printf("%v月是31天\n",month)
case 2 :
if year % 4 == 0 {
fmt.Printf("%v月是28天\n",month)
} else {
fmt.Printf("%v月是29天\n",month)
}
case 4,6,9,11 :
fmt.Printf("%v月是30天\n",month)
default:
fmt.Println("输入月份错误,请重新输入")
continue
}
} else {
fmt.Println("程序退出")
break
}
}
}
func main() {
test()
}
练习29:编写一个函数,随机猜数游戏:随机生成一个1-100的整数,有十次机会,如果第一次就猜中 提示
你真是个天才”如果第2—3次猜中,提示“你很聪明,赶上我了”如果第4—9次猜中,提示“一般般”如果最后次猜中,提示“可算猜对啦”十次都没猜对,提示“说你点啥好呢”
package main
import (
"fmt"
"math/rand"
"time"
)
func number() {
var inPut int
var num int
var cut int = 10
for {
fmt.Println("请输入一个数")
fmt.Scanln(&inPut)
num++ //每输入一个数就累加一次
//生成一个随机数
rand.Seed(time.Now().UnixNano())
numder := rand.Intn(100) + 1
fmt.Println(numder)
if inPut == numder { //判断两个数是否相等
if num == 1{
fmt.Println("你真是个天才")
break
} else if num == 2 || num == 3 {
fmt.Println("你很聪明,赶上我了")
break
} else if num >= 4 || num <= 9 {
fmt.Println("一般般")
break
} else {
fmt.Println("可算猜对啦")
break
}
} else {
cut-- //每猜错一次机会减一
if cut != 0{
fmt.Printf("你还有%v次机会",cut)
} else {
fmt.Println("说你点啥好呢")
break
}
}
}
}
func main() {
number()
}
练习30:编写一个函数:输出100以内的所有素数每行显示5个;并求和
package main
import (
"fmt"
)
func number(nun int) {
var a1 int
var num int
for i := 2; i <= nun; i++ {
var count int
for j := 2; j < i; j++ {
if i % j == 0 {
count++
}
}
if count == 0{
fmt.Print("\t",i)
num += i
a1++
if a1 %5 == 0{
fmt.Println()
}
}
}
fmt.Println("素数和为:",num)
}
func main() {
var a1 int
fmt.Println("请输入要求的素数")
fmt.Scanln(&a1)
number(a1)
}
进阶60题
练习31:编写-个函数,判断是打鱼还是晒网,中国有句俗语叫“三天打鱼两天晒网”。如果从1990年1月1日起开始执行“三天打鱼两天晒网”。如何判断在以后的某一天中是“打鱼”还是“晒网”?
package main
import (
"fmt"
)
//定义一个函数
func days(year int,month int,day int) {
var count int
for i := 1990; i < year; i++ {
if i % 4 == 0 {
count += 366
} else {
count += 365
}
}
for j := 1; j <= month-1; j++ {
switch j {
case 1,3,5,7,8,10,12:
count += 31
case 4,6,9,11:
count += 30
case 2:
if year % 4 == 0 {
count += 29
}else {
count += 28
}
}
}
count += day
fmt.Println("一共相距:",count)
if count % 5 == 0 || count % 5 == 4 {
fmt.Println("晒网")
}else {
fmt.Println("打鱼")
}
}
func main(){
for {
var year int
var month int
var day int
fmt.Println("请输入年份:")
fmt.Scanln(&year)
if year == 0 {
break
}
fmt.Println("请输入月份:")
fmt.Scanln(&month)
fmt.Println("请输入日期")
fmt.Scanln(&day)
days(year,month,day)
}
}