#3 Swift的變數和常數練習
(Variable & Constant)
習題來源: We Love Swift
1.1 Sum
You are given two variables a
and b
, compute their sum and store it in another variable named sum
then print the result.
1.2 Seconds
Determine the number of seconds in a year and store the number in a variable named secondsInAYear
.
1.3 Pixels
Your are given the width
and height
of a screen in pixels. Calculate the total number of pixels on the screen and store the result in a variable named numberOfPixels
.
1.4 Sum and Difference
You are given the sum
and the difference
of two numbers. Find out the values of the original numbers and store them in variables a
and b
.
1.5 L Area
You are given four variables width
, height
, x
, y
that describe the dimensions of a L-shape as shown in the image below. Determine the perimeter
and area
of the described L-shape. Store the value of the perimeter in a variable named perimeter
, and the area in a variable named area
.
1.6 Swap
Given two variable a
and b
, swap their values. That is the new value of a
will become the old value of b
and vice versa.
1.7 Last digit
You are given a number a
. Print the last digit of a
.
1.8 Dog Years
You are given Rocky’s age in dog years. Print Rocky’s age in human years. You know that 1 human year is 7 dog years.
1.9 Brothers
Everyone hates solving word problems by hand so let’s make a program to solve them for us.x
years from now Alice will be y
times older than her brother Bob. Bob is 12
years old. How many years does Alice have?
1.10 Apples and Oranges
You have x
apples. Bob trades 3
oranges for 5
apples. He does not accept trades with cut fruit.
How many oranges can you get from Bob and how many apples will you have left?
The number of apples you will have left should be stored in a variable named apples
. The number of oranges you will have after the trade should be stored in a variable named oranges
.
1.11 Boys and Girls
A class consists of numberOfBoys
boys and numberOfGirls
girls.
Print the percentage of boys in the class followed by the percentage of girls in the class. The percentage should be printed rounded down to the nearest integer. For example 33.333333333333
will be printed as 33
.