【问题标题】:How to get the sum of two index in an array in C?如何获得C中数组中两个索引的总和?
【发布时间】:2019-01-23 02:54:00
【问题描述】:

我正在为具有动态大小的数组编写代码并手动填充数组。然后,它将打印。它还会询问一个数字并找到与两个索引相等的索引。

我为此代码使用代码块。 id 尝试 for 循环查找与输入数字相等的两个索引。

#include <stdlib.h>
#include <stdio.h>

void printArray(int *array, int size) {
    printf("["); 
    for (int i = 0; i < size - 1; i++) {
        printf("%i,", array[i]);

    }
    if (size >= 1)
        printf("%i", array[size-1]); 
        printf("]\n");

    int num;
    printf("Enter number to be calculate: ");
    scanf("%d",num);

    for(int i= 0; i < size - 1; i++){
        if (array[i] + array[size-1] == num){
            printf("%d  %d", array[i],array[size-1]);
        }
        size--;
    }
}

int main(void) {
    int count;
    int num;
    int sum;
    printf("Enter the size of the array:\n");
    scanf("%d", &count);

    int *array = malloc(count * sizeof(*array));
    if (!array) {
        printf("There was a problem you entered");
        exit(EXIT_FAILURE);
    }

    printf("Enter the elements of the array:\n");
    for (int i = 0; i < count; i++)
    scanf("%d", &array[i]);

    printArray(array, count);
}

我期望输出:

索引 1 和 5 等于输入的数字。 但它给出了错误。

【问题讨论】:

    标签: c arrays for-loop


    【解决方案1】:

    首先,以下错误是问题之一 -

    scanf("%d",num);
    

    应该是-

    scanf("%d", &num);
    

    【讨论】:

    • 谢谢你,但我仍然无法添加两个索引。我找不到满足输入数字的索引。
    • 请提及您尝试过的输入。预期和实际输出。
    • 如果两个索引相加并且和等于输入的数字,则打印两个索引。如果不是,它将打印不匹配的数据。
    • 这个链接可能对link有帮助
    【解决方案2】:

    printArray 中的最后一个循环基本上是同时向上和向下遍历数组一个元素。

    因此,对于 n=6,如果 (a[0]+a[5])、(a[1]+a[4]) 或 (a[2]+a[3 ]) 不等于所需的数字,它将显示为不匹配。

    此循环应替换为嵌套循环,以便内部循环从 j=i+1 迭代到 size-1 以允许检查 a[i]+a[j] == num用于数组索引的所有可能排列。

    【讨论】:

    • 这是正确的代码吗? for(int i= 0; i
    • 看起来不错。只需将 i 迭代到 size -2 而不是 size -1 ` for(int i=0; i
    • 知道了。谢谢..我得到了正确的索引。如果没有索引与我输入的内容匹配,我可以知道放在哪里吗?我放在循环内,但它也打印了很多次。
    • 您可以在循环外定义一个布尔变量,默认值为 false。在打印匹配发生时,在循环内将其设置为 true。如果循环结束后该值仍然为 false,则可以打印语句“找不到匹配项”。为了避免多次打印,一旦变量设置为 true,您就可以中断。
    猜你喜欢
    • 2017-07-10
    • 2013-11-29
    • 1970-01-01
    • 2020-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多