假设我们要去火星,但是有多条航线,每条航线的时间,票的类型(单程,往返)、价格都不同;
- 使用变量、常量、if、for、fmt、math/rand等编写这个程序,随机生成格式数据列表。
- 一共四列
- Spaceline 是航空公司:Space Adventures、SpaceX、Virgin Galactic。
- Days 是指到火星单程所需的天数:距离火星的距离为62,100,000公里,速度随机生成16-30km/s。
- Trip Type 是指单程还是往返。
- Price 单位是万美元:票价随机生成3600万-5000万之间(单程)
按题目要求用go编写的结果
package main
import (
"fmt"
"math/rand"
"strconv"
"time"
)
func init() {
//初始化随机种子
rand.Seed(time.Now().UnixNano())
}
func main() {
fmt.Printf("%-16v","Spaceline")
fmt.Printf("%6v ","Days")
fmt.Printf("%-15v","TripType")
fmt.Printf("%10v\n","Price")
var company = [3]string{"Space Adventures","SpaceX","Virgin Galactic"} //公司名称
const distance = 62100000 //到火星距离
const startSpeed = 16 //开始速度
const endSpeed = 30 //结束速度
const startPrice = 3600 //开始金额
const endPrice = 5000 //结束金额
var price float64 //随机金额
var speed = 0 //随机速度
//华丽的分隔线
fmt.Println("=================================================")
//遍历单程与往返列表
for i := 0; i < (len(company)*2); i++ {
if i%2 == 0 {
speed = startSpeed + rand.Intn(endSpeed - startSpeed)
price = float64(startPrice + rand.Intn(endPrice - startPrice)) + rand.Float64()
fmt.Printf("%-16v",company[i/2])
fmt.Printf("%6v ",distance/(speed * 3600 * 24))
fmt.Printf("%-15v","One-way")
fmt.Printf("$%9.2f\n",price)
} else {
fmt.Printf("%-16v",company[(i-1)/2])
fmt.Printf("%6v ",(distance/(speed * 3600 * 24))*2)
fmt.Printf("%-15v","Round-Trip")
//处理往返时第三小数问题
price, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", price), 64)
fmt.Printf("$%9.2f\n",price * 2)
}
}
}
按题目要求用rust编写的结果
use rand::Rng;
fn main() {
print!("{: <16}","Spaceline");
print!("{: >6} ","Days");
print!("{: <12}","TripType");
println!("{: >10}","Price");
let company = ["Space Adventures","SpaceX","Virgin Galactic"]; //公司名称
const DISTANCE:i32 = 62_100_000; //到火星距离
let start_speed = 16; //开始速度
let end_speed = 30; //结束速度
let start_price = 3600.0; //开始金额
let end_price = 5000.0; //结束金额
let mut price:f64 = 0.0; //随机金额
let mut speed = 0; //随机速度
//华丽的分隔线
println!("===============================================");
//遍历单程与往返列表
for i in company.iter() {
let mut x = 0;
while x < 2 {
if x == 0 {
speed = rand::thread_rng().gen_range(start_speed..end_speed);
price = rand::thread_rng().gen_range(start_price..end_price);
print!("{: <16}",i);
print!("{: >6} ",DISTANCE/(speed * 3600 * 24));
print!("{: <12}","One-way");
println!("${: >10.2}",price);
} else {
print!("{: <16}",i);
print!("{: >6} ",(DISTANCE/(speed * 3600 * 24))*2);
print!("{: <12}","Round-Trip");
println!("${: >10.2}",format!("{:.2}",price).parse::<f64>().unwrap() as f64 * 2.0); //处理往返时第三小数问题
}
x += 1;
}
}
}