【发布时间】:2018-04-12 20:12:46
【问题描述】:
我目前正在为我的编程课完成一项学校作业。在这个作业中,我们创建了一个函数,它接受一个数字等级(一个 Double)并将它除以 numberOfHours 以获得一个 GPA 变量。我在我的代码中遇到了一个错误:
二元运算符“+”不能应用于“Double”和“Int”类型的操作数
我不明白这个错误,我正在尝试通过更改什么是 Int 和什么是 Double 来修复代码,但它似乎不起作用。
错误来自的代码是:
// create your function here
func gpaUpdater(moreHours hours: Double, moreGPA grade: Double) -> Int {
let addedHours: Int = hours + attemptedHours
let calculatedGPA: Double = hours / grade
//gpa = gpa + grade
print(calculatedGPA)
return calculatedGPA
}
完整代码如下:
// My Functions Playground.swift
//
//
//: Playground - noun: a place where people can play
import UIKit
/*
We're going to track your GPA from one semester to the next. Assume at the end of your sophomore years, you have attempted 60 hours and have earned 222.5 grade points. Assign attempted hours and grade points to variables. Write a function that updates your current GPA and assigns it to the GPA var (you'll update it along the way). Label your function arguments. Print your new GPA from within the function.
At the end of the current semester, add 16 hours and 60 grade points to your record. Call the gpa function to update your overall gpa.
Test your gpa at the end of the year to see if any administrative action needs to be taken. If the gpa is less than 1.8, the student will need to be placed on suspension. If less than 2.0, we need to put the student on probation. If over 3.5, we'll put the student on the dean's list, and if over 3.9, we'll put the student on the president's list. Create a switch that prints the recommended adminstrative action. If no action is required, print, "Carry on. Nothing to see here." Create internal and external labels for your arguments.
*/
var gpa: Double
var attemptedHours: Int
var earnedGradePoints: Int
// create your function here
func gpaUpdater(moreHours hours: Double, moreGPA grade: Double) -> Int {
let addedHours: Int = hours + attemptedHours
let calculatedGPA: Double = hours / grade
//gpa = gpa + grade
print(calculatedGPA)
return calculatedGPA
}
// call the function
gpaUpdater(moreHours: 16, moreGPA: 60)
// add the new hours and grade points here and call the function again
func switchFunction() {
switch gpa {
case gpa..<1.8:
print("You will be placed on suspension")
case 1.8...2.0:
print("You will be placed on probation")
case 3.5...3.8:
print("You will be put on the dean's list.")
case 3.9..<gpa:
print("You will be put on the president's list.")
default:
print("Carry on. Nothing to see here.")
}
}
switchFunction()
【问题讨论】: