[英]Where is the logic wrong in my code?
請原諒我的英語。
我正在上C的入門課程,我的程序邏輯存在一些問題。 它有時只會產生所需的輸出。
任務是編寫一個獲取數組元素的函數,返回元素中最大的偶數位。
int ary1[] = {123, 456, -7890, 12};
將-7890
作為最大值返回,其中8
為最大偶數及其出現次數。
int ary2[5] = {-123, 654, 78, 15, 189};
返回189
作為最大值,其中8
作為最大偶數及其出現次數。
int ary3[2] = {9, 9};
什么都不會回來。
int ary4[] = {123, 123, 0, 12};
將123
返回為最大值,其中2
為最大偶數及其出現次數。
int ary5[] = {24, 45, -789, 24, 1};
將-789
作為最大值返回,其中8
為最大偶數及其出現次數。
int ary6[] = {-749, -241, 1, 45};
將45
作為最大值返回,其中4
為最大偶數及其出現次數。
這是我的代碼:
#include <stdio.h>
void digitExtract(int[], int);
int main() {
int ary1[] = { 123, 456, -7890, 12 };
int ary2[5] = { -123, 654, 78, 15, 189 };
int ary3[2] = { 9, 9 };
int ary4[] = { 123, 123, 0, 12 };
int ary5[] = { 24, 45, -789, 24, 1 };
int ary6[] = { -749, -241, 1, 45 };
int ary7[] = { 1, 3, 5 };
printf("\nCalling function in ary1[]:\n");
digitExtract(ary1, 4);
printf("\nCalling function in ary2[]:\n");
digitExtract(ary2, 5);
printf("\nCalling function in ary3[]:\n");
digitExtract(ary3, 2);
printf("\nCalling function in ary4[]:\n");
digitExtract(ary4, 4);
printf("\nCalling function in ary5[]:\n");
digitExtract(ary5, 5);
printf("\nCalling function in ary6[]:\n");
digitExtract(ary6, 4);
printf("\nCalling function in ary7[]:\n");
digitExtract(ary7, 3);
}
void digitExtract(int Array[], int array_size) {
int tempValue;
int x;
int myArr[10] = { 0 };
int evenCount = 0;
int max = Array[0];
for (int i = 1; i < array_size; i++)
{
if (Array[i] < 0) {
Array[i] = -Array[i];
if (Array[i] > max) {
max = Array[i];
}
}
}
tempValue = (max < 0) ? -max : max;
do {
myArr[tempValue % 10]++;
tempValue /= 10;
} while (tempValue != 0);
for (x = 8; x > 0; x -= 2) {
if (myArr[x]>0) {
printf("Displaying from inside of function():\n");
printf("\nThe largest even digit: %d\n", x );
printf("\nThe digit %d occurs %d times.\n", x, myArr[x]);
evenCount++;
break;
}
} if (evenCount == 0)
printf("\nNo even digits found!\n\n");
}
我知道我的邏輯中有一個錯誤,因為ary2[]
它會產生6
的偶數,當它應該是8
時它會出現,但我不知道在哪里。
該函數適用於具有奇數值的數組作為其元素。
哪里或我做錯了什么?
謝謝。
你的任務是找到最大的甚至數字,然后找到具有該數字的最大價值...... 找不到最大的價值,然后在其中找到最大的,甚至兩位數。
我將首先編寫一個名為max_even_digit
的函數來對單個int
進行操作,然后驗證並從那里開始工作。
int max_even_digit(int x) {
int max = 0;
while (x) {
int digit = x % 10;
digit = digit < 0 ? -digit : digit;
if (x % 2 == 0 && digit > max) {
max = digit;
}
x /= 10;
}
return max;
}
完成此操作后,循環遍歷數組,就像找到最大值一樣,但讓max_even_digit
的返回值優先於實際值。
int max_even_digit_value(int *array, size_t size) {
if (size == 0) {
return 0;
}
int max_value = array[0],
max_digit = max_even_digit(max_value);
while (--size) {
int value = array[size],
digit = max_even_digit(value);
if (digit > max_digit || (digit == max_digit && value > max_value)) {
max_value = value;
max_digit = digit;
}
}
return max_value;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.