c - 如何获取数组最后一个元素的值?

标签 c arrays

遵守以下代码。我想将数量除以数组中最后一个元素的值。我尝试了以下方式,但它不起作用。谁能告诉我正确的方法是什么?

#include<stdio.h>
int main()
{
    int i, j, k, noteNumber, array[100], amount, result;

    printf("Enter the number of the notes: \n");
    scanf("%d", &noteNumber);

    printf("Enter the value of %d notes: \n", noteNumber);
    for(i = 0; i < noteNumber; i++){
        scanf("%d", &array[i]);
    }

    printf("Enter the amount: \n");
    scanf("%d", &amount);

    i = j;

        if(amount / array[j] == 0){
        printf("Minimum %d number of is needed", (amount/array[j]));
        printf("The value of each note is %d", array[j]);
    }

}

最佳答案

如我所见

  i = j;

是错误的,因为您正在使用未初始化变量的值分配给另一个变量。这没有任何意义,可能导致 undefined behavior .

C 数组使用从 0 开始的索引,因此对于大小为 n 的数组,最后一个索引将为 n-1

就是说,永远不要对静态定义的数组使用未绑定(bind)索引,在使用索引之前始终执行绑定(bind)检查。

关于c - 如何获取数组最后一个元素的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41858212/

相关文章:

c - 如何使用 perror 打印变量

c - 数组上的就地位反转随机播放

android - 如何从包含android中字符串数组类型列的解析类中获取值

java - 错误: "A JSONArray text must start with ' [' at 1 [character 2 line 1]" should not apply

javascript - 二维数组 - 将对象添加到字段

c - 使用 goto 跳过变量声明?

c - 我无法使用 cmake 和 MinGW gcc 编译器构建 gtk gui

c - 为什么使用在 32 位和 64 位之间切换的通用 Int 比显式使用 Int32 和 Int64 更好

c++ - 是否有静态分析器可以检查 C/C++/Objective-C 中的局部变量重新分配?

c++ - cin.getline 在 for 循环中搞砸了