Potentiation with array

Asked

Viewed 53 times

0

I thought of the following code to calculate the square of each value in array:

double []vetor =  {1,2,3,4,5,6,7,8,10};
        double result = 0;
          foreach(double posicao in vetor){
              result = Math.Pow(posicao, 2);
              vetor[result] = result;
          }  
          Console.WriteLine($"{String.Join(" , ", vetor)}.");

This error appears:

error CS0266: Cannot implicitly Convert type double' to int'. An Explicit Conversion exists (are you Missing a cast?)

  • Your code problem is in: vector[result], the array indexer expects an integer, but you are accessing with a double.

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site.

1 answer

1

Do not need to do this gambiarra, leave whole and do without using auxiliary function (understood that only use double to use the function). But you cannot use foreach when you change the collection element you have to use the for normal, then it would be like this:

using static System.Console;

public class Program {
    public static void Main()   {
        int []vetor =  { 1, 2, 3, 4, 5, 6, 7, 8, 10 };
        for (int i = 0; i < vetor.Length; i++ ) vetor[i] *= vetor[i];
        WriteLine($"{string.Join(", ", vetor)}.");
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.