函数错误:“二进制运算符'+'不能应用于'Double'和'Int'类型的操作数”

时间:2018-04-05 20:49:30

标签: swift function

我目前正在为我的编码班完成一项学校作业。在这个赋值中,我们创建了一个带有数字等级(双精度)的函数,并将其除以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()

1 个答案:

答案 0 :(得分:0)

更改此行

let addedHours: Int = hours + attemptedHours

let addedHours =  Int(hours) + attemptedHours