Reputation: 47
I need to define and call a function called areaOfRectangle
that takes two Int
parameters, length
, and width
, and prints the result of length * width
. I actually got result with length * width
but it is telling me to make sure I’m defining a function with the correct name and parameters. The answer below will print length * width
which is right but the steps are not what it should be.
func areaOfRectangle(length: Int, width: Int) {
print(“length * width”)
}
areaOfRectangle(length: 0, width: 0)
Upvotes: 1
Views: 5355
Reputation: 1
Explaination: function with multiple parameters., in which the function greet have parameter of alreadyGreeted also a condition it will check when we give argument label of person and bool is true, we call it, and function will start its execution... condition is checked,. then greetAgain function is called with its argument label... and print "hello Again" with person name that is in greet-main function calling parameter.
Upvotes: -1
Reputation: 3666
print(“length * width”)
in this statement length and width are being treated as string literals. Any thing that comes between "" is a string literal at least in swift, also in some other languages.
Swift provide a very good syntactic sugar to use variables and constants within the string by putting the vars
and lets
within \()
. Hence when you correct the above statement to print(“\(length * width)”)
. It will print correct result of length*width.
Updated code:
func areaOfRectangle(length: Int, width: Int) {
print(“\(length * width)”) //42
}
areaOfRectangle(length: 6, width: 7)
Upvotes: 0
Reputation: 71854
Here is the way you can return
string result from Int
parameters:
//define a return type as String here
func areaOfRectangle(length: Int, width: Int) -> String {
print("\(length * width)") //same thing you can print here
return "\(length * width)" //return it as String
}
let result = areaOfRectangle(length: 5, width: 5)
print(result) //"25"
Upvotes: 1
Reputation: 722
You have defined the function correctly but made a small mistake in the front statement as it will always print length * width in the output console as its a string not the operator or operands. Here is the solution
func areaOfRectangle(length: Int, width: Int) {
print("\(length * width)")
}
areaOfRectangle(length: 0, width: 0)
just added '\'() in the print statement
Upvotes: 1