There is an array of 10 int numbers to calculate the product of elements with indices that are degree 2. I wrote this code, but it calculates that the value is 0, although there are no zeros anywhere. The array is filled by the user through the Textbox. Unused variables will be needed for the next task.

namespace WindowsFormsApp7 { public partial class Form1 : Form { int[] md = { }; int[] M = new int[10]; int inputCount = 0; int sum = 0; int sum1 = 0; int min1 = int.MaxValue; int min2 = int.MaxValue; int min3 = int.MaxValue; double sumabs = 0; int mul = 1; double multavg = 1; int A; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { int A; if (int.TryParse(textBox1.Text, out A) && inputCount < 10) { M[inputCount] = A; inputCount++; label3.Text += A.ToString() + ", "; } int idx = 1; while (idx < M.Length) { mul *= M[idx]; idx *= 2; } } public void Res() { label3.Text += "\r\n" + "Произведение элементов с индексами, являющимися степенью 2: " + mul.ToString(); } private void timer1_Tick(object sender, EventArgs e) { if (inputCount >= 10) { Res(); timer1.Stop(); } } } } 
  • if d in the range from 0 to 10, why check the power of two more than 3? - Grundy
  • In the next task, the array will be dynamic. - Randomusername

1 answer 1

No need to compare an integer with the devil knows what. And in general, it is not necessary to check the indices - just enough to go through the necessary indices. Ideone

 using System; public class Test { public static void Main(){ int[] M = new int[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int mul = 1; int idx = 1; while (idx < M.Length) { mul *= M[idx]; idx *= 2; } Console.WriteLine(mul); } } >> 270 
  • It looks right, but I still get 0, the only place where I still touch the mul variable is when outputting the result: label3.Text + = "\ r \ n" + " ; Where then could be the error? - Randomusername
  • Led the real working code. Where is the error - I can not know, I do not see the code. - MBo
  • Added the entire code, can you see? - Randomusername
  • You need to debug and make sure the contents of the array. Now I see that one number is entered, and after that the whole array is processed - and the rest can be (or should) be filled with zeros. Either enter a list of numbers, or process only after filling the entire array (if inputCount) - MBo
  • Why generate an array of indexes if you can just use for? - Qwertiy