I tried this question on R programming but for some reason, my code doesn't seem to work. Could someone please explain where I'm wrong? Thanks.
largenumbers <- function(d,e,f) {
if{d==e & e==f & f==d}
print("Please provide different numbers")
else{
Largest <- max(c(d,e,f))
SecondLargest <- max(c(d,e,f)[-which.max(c(d,e,f))])
return(Largest^2 SecondLargest^2)
}
}
largenumbers(4,5,6)
CodePudding user response:
if (condition) {
do
} else {
do
}
in your function, problem is if{d==e & e==f & f==d}
. It should be if(d==e & e==f & f==d)
. Formal version is
largenumbers <- function(d,e,f) {
if(d==e & e==f & f==d){
print("Please provide different numbers")}
else{
Largest <- max(c(d,e,f))
SecondLargest <- max(c(d,e,f)[-which.max(c(d,e,f))])
return(Largest^2 SecondLargest^2)
}
}
largenumbers(4,5,6)
[1] 61
CodePudding user response:
Apart from the syntax issue with if
, I think you also have a logical issue. Instead of &
the condition should be |
(or even better ||
as the values are scalar) to avoid any duplicate value.
You may also use sort
, then select last 2 values and return sum of squares.
largenumbers <- function(d,e,f) {
if(d==e || e==f || f==d)
stop("Please provide different numbers")
else{
num <- sort(c(d, e, f))
return(sum(tail(num, 2)^2))
}
}
largenumbers(4,5,6)
#[1] 61
largenumbers(10, 12, 6)
#[1] 244
largenumbers(10, 12, 12)
Error in largenumbers(10, 12, 12) : Please provide different numbers