Click here to Skip to main content
15,886,840 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
static void srednia_arytmetyczna()
{
int suma = 0;
double srednia;
Console.WriteLine("Z ilu liczb chcesz obliczyć średnią arytmetyczną?");
int ile_liczb = Convert.ToInt32(Console.ReadLine());
int[] liczby = new int[ile_liczb];
for (int i = 0; i < liczby.Length; i++)
{
Console.WriteLine("Podaj {0} liczbę", i + 1);
liczby[i] = Console.ReadLine();
}
for (int i = 0; i < liczby.Length; i++)
{
Console.Write(liczby[i] + ", ");
suma += liczby[i];
}
srednia = (double)suma / liczby.Length;
Console.WriteLine();
Console.WriteLine("Średnia: {0}", srednia);
Console.ReadKey();
}
Cannot implicitly convert type 'string' to 'int'
Line 66 => liczby[i] = Console.ReadLine();

What I have tried:

I tried to change some things but without consequence
Posted
Updated 19-Nov-16 1:12am
Comments
Philippe Mori 19-Nov-16 14:54pm    
Use a code block to format your code.

Console.ReadLine returns a string. You cannot assign that to an integer variable or member of integer array.

First thing would be to look at validating the user input.
Take a look at the int.TryParse method. It will validate the user input, and convert it to an integer, all in the one go

something like
C#
while (int.TryParse(Console.ReadLine(), out liczby[i]) == false)
    Console.WriteLine("Try again");
 
Share this answer
 
C# is not a typeless language. You have to cast/convert/parse the string into an integer.

C#
string inputStr = Console.ReadLine();
int inputInt;
if (int.TryParse(inputStr, out inputInt)
{
    liczby[i] = inputInt;
}
else
{
   // invalid input string (could not be converted to an integer)
}
 
Share this answer
 
v2
liczby[i] is an int array
C#
int[] liczby = new int[ile_liczb];

You need to convert string (Console.Readline()) to int before assignment.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900