Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialJustin Molyneaux
13,329 PointsReturn the average length of the tongues of the frogs in the array. Use a for loop as part of your solution.
How do I solve this challenge problem?
I keep getting an error that says, "Cannot Implicitly convert Frog.Cs to double."
using System;
namespace Treehouse.CodeChallenges
{
class FrogStats
{
public static double GetAverageTongueLength(Frog[] frogs)
{
double total = 0;
int i = 0;
double sum = 0;
for(; i < frogs.Length; i++)
{
sum = (double)frogs[i];
total += sum;
}
//Console.WriteLine(avg/i);
}
}
}
namespace Treehouse.CodeChallenges
{
public class Frog
{
public int TongueLength { get; }
public Frog(int tongueLength)
{
TongueLength = tongueLength;
}
}
}
2 Answers
Yi Chiang
11,738 Pointsfrogs is array and frogs[i] is one of constructor. You can access tongueLength by using frogs[i].TongueLength frogs[i].TongueLength is double data type.
for(; i < frogs.Length; i++)
{
sum = (double)frogs[i];
total += sum;
}
I will suggest to use this kind...
for(int i = 0; i < frogs.Length; i++)
{
}
My answer is
namespace Treehouse.CodeChallenges
{
class FrogStats
{
public static double GetAverageTongueLength(Frog[] frogs)
{
double total=0;
for(int i=0;i<frogs.Length;i++)
{
total+=frogs[i].TongueLength; //frogs[i].ToLength is double data type
}
return total/frogs.Length; //average = total / sum of item
}
}
}
Steven Parker
231,268 PointsRemember, you're averaging the tongue lengths, not the frogs themselves.
Since a frog isn't just a value, it cannot be converted to a double by casting.
You'll also need to take care of these issues:
- after adding the lengths, you'll need to divide by the number of frogs to get an average
- your function will need to return the average value
Justin Molyneaux
13,329 PointsThank you for guiding me to the solution.
Justin Molyneaux
13,329 PointsJustin Molyneaux
13,329 PointsThank you for showing me to the solution and providing comments.
HIDAYATULLAH ARGHANDABI
21,058 PointsHIDAYATULLAH ARGHANDABI
21,058 PointsTry this answer this method works.