נתון מערך בעל 10 איברים. על המערך להדפיס רק איברים שקטנים מממוצע ונמצאים במקומות אי זוגיים, נוסף על כך עליהם להתחלק ב 3 ללא שארית.
כתבתי את זה ולא הבנתי איך להמשיך
אשמח לעזרה
תודה
int[] a = new int[10];
int i, n, sum = 0;
Console.Write("Input the number of elements to be stored in the array :");
n = Convert.ToInt32(Console.ReadLine());
Console.Write("Input {0} elements in the array :\n",n);
for (i = 0; i < n; i++) {
Console.Write("element - {0} : ",i);
a[i] = Convert.ToInt32(Console.ReadLine());
}
for (i = 0; i < n; i++) {
sum += a[i];
}
int[] a = new int[10];
int i, n, sum = 0, average = 0;
Console.Write("Input the number of elements to be stored in the array:");
n = Convert.ToInt32(Console.ReadLine());
if (n <= 0) {
Console.Write("Please use a postive integer");
return;
}
Console.Write("Input {0} elements in the array:\n",n);
for (i = 0; i < n; i++) {
Console.Write("element - {0}:",i+1);
a[i] = Convert.ToInt32(Console.ReadLine());
}
// Sum the values
for (i = 0; i < n; i++) {
sum += a[i];
}
// Calculate the average
average = sum / n;
// Print the valid numbers
Console.Write("\nPrinting the result:\n");
for (i = 0; i < n; i++) {
if (a[i] < average && i % 2 != 0 && a[i] % 3 == 0) {
Console.Write("{0} ",a[i]);
}
}
השינויים:
קודם כל, הוספתי בדיקה לקלט של מספר האיברים - הוא צריך להיותר מספר חיובי שלם גדול מאפס.
שיניתי את ההדפסה בתוך הלולאה הראשונה להיות i+1 ולא i.
חישבתי את הממוצע average על-ידי חלוקה של סכום האיברים במספר האיברים.
בלולאה האחרונה, אנחנו עוברים על איברי המערך ובודקים עבור כל תא במערך אם הוא מקיים:
האיבר קטן מהממוצע : a[i] < average.
נמצא במקומות אי-זוגיים: i % 2 != 0.
האיבר מתחלק ב-3 ללא שארית: a[i] % 3 == 0.
לדוגמה, עבור המספרים 3,6,9,12,15,18,21,24,27,30 נקבל כי הממוצע הוא 12.6 ולכן האיברים שיודפסו הם 6 (כי הוא נמצא באינדקס אי-זוגי 1, כפולה של 3 וקטן מהממוצע) ו-12 (כי הוא נמצא באינדקס אי-זוגי 3, כפולה של 3 וקטן מהממוצע).