获取以0结尾的数组中的最大元素

Get the max element in an array that ends with a 0

本文关键字:元素 数组 结尾 获取      更新时间:2023-10-16

因此,我正在编写一个代码,该代码创建一个数组,其中包含用户编写的元素和元素数量,然后代码生成最后一个数字为零的最大值。因此,我已经完成了编写一个数组的步骤,其中包含用户输入的元素。最难的部分(对我来说)是完成生成最后一个数字为零的最大值的代码。是的,我需要一个建议来完成这个代码。谢谢你。

例如:

a array - 2 20 25 300 55555最后一位为零的最大数字是300

所以,是的,我需要一个建议来完成这段代码。下面是我到目前为止所做的代码:

#include "stdafx.h"
#include <stdlib.h>
#include <windows.h>
#include <time.h>
int GetAmount() {
    int howmany;
    printf("Enter amount of elements - ");
    scanf_s("%i", &howmany);
    return howmany;
}
void GetArray(int a[], int n) {
    printf("Enter elements - n");
    for (int i = 0; i < n; i++)
    {   printf("%i ->", i);
        scanf_s("%i", &a[i]);
    }
}
int LastDigitZero(int n[], int a) {
    for (int i = 0; i < a; i++)
    {
        if (n[i] % 10 == 0) {
            return 0;
        }
    }
}
int maxvalue(int a[], int n) {
    int temp = 0;
    for (int i = 0; i < n; i++)
    {
        if (a[i] > temp) {
            temp = a[i];
        }   
    }
    return temp;
}

void main() {
    int amount = GetAmount();
    int array[100];
    GetArray(array, amount);
    int max = maxvalue(array, amount);
    printf("Max Value is %in", max);
}
谢谢您的关注,祝您愉快!:)

成功了!这就是它的样子!

#include "stdafx.h"
#include <stdlib.h>
#include <windows.h>
#include <time.h>
int GetAmount() {
    int howmany;
    printf("Enter amount of elements - ");
    scanf_s("%i", &howmany);
    return howmany;
}
void GetArray(int a[], int n) {
    printf("Enter elements - n");
    for (int i = 0; i < n; i++)
    {   printf("%i ->", i);
        scanf_s("%i", &a[i]);
    }
}

int maxvalue(int a[], int n) {
    int temp = 0;
    for (int i = 0; i < n; i++)
    {
        if (a[i] % 10 == 0 && a[i] > temp) {
            temp = a[i];
        }   
    }
    return temp;
}

void main() {
    int amount = GetAmount();
    int array[100];
    GetArray(array, amount);
    int max = maxvalue(array, amount);
    printf("The biggest number which last digit is zero is %in ", max);
    system("pause");
}

谢谢大家的回答!太快了!!:)

你就快成功了。首先,任何以0结尾的数对10 mod后都是0这就是检验最后一位数是否为0的方法。然后将maxvalue()更改为

int maxvalue(int a[], int n) {
    int temp = a[0];
    for (int i = 1; i < n; i++)
    {
        if (a[i] % 10 == 0 && a[i] > temp) {
            temp = a[i];
        }   
    }
    return temp;
}

我还做了一个改变,将temp设置为a[0]的值,如果你的数组都是负数,那么0将是最大的数字。因为temp已经是a[0]了,所以我们可以在1处开始for循环。

你应该检查是否有一个解决方案,在这个例子中,你可以检查maxValue返回的值结束于0(如果没有值结束于0,那么它将返回一个[0]):

int maxValue(int a[], int n) {
    int temp= a[0]
    for (int i(1); i<n;i++) {
        if (a[i] % 10 == 0 && (temp % 10 != 0 || a[i] > temp )) temp = a[i];
    }
    return temp;
}