【问题标题】:Addition of products of (first and last), (second and last but 1) and so on numbers of an array(第一个和最后一个),(第二个和最后一个但1)的乘积相加等等数组的数字
【发布时间】:2018-05-19 04:16:05
【问题描述】:
#include<stdio.h>

int main()
{
    int n;
    printf("Enter the size of array");
    scanf("%d",&n);
    int array[n-1];

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

    int product = 0;

    for(int i=0; i<n; i++)
    {

这里我提出的条件是,当所有独特的产品都结束时,退出循环并打印输出。

        if(i>(n-1-i))
        {
            break;
        }
        int f = array[i];
        int l = array[n-i];

        product = product + (f*l);
    }
    printf("Result: %d",product);
    return 0;
}

对于 {1,2,3,4,5,6,7,8,9,10} 的数组,我得到的结果是 4206199。正确答案是 110。

【问题讨论】:

  • 故意创建一个太小的数组似乎是一个糟糕的开始。当你声明 int array[n-1]; 时,你只有元素 array[0]..array[n-2] 可以使用——但是你的循环试图写入 array[n-1],这是未定义的行为,因为你正在写超出数组的末尾。从声明中删除-1
  • 同时使用从 0 到 n-1 的 i 访问 n-i 感觉不好。当最大值为 n-1 时,您的第一次访问是 array[n](在修复数组定义中的错误之后)。
  • 你还需要考虑你的主循环。目前,您将 A0 和 A9 以及 A9 和 A0 相乘和相加。这使总和翻了一番。但是,您的数组大小错误可能是其余大部分问题的原因。您应该打印正在相乘和相加的索引和值,以便了解计算是如何进行的,或者使用代码中的printf() 语句或使用您的调试器。
  • 您可能想阅读以下内容:How to debug small programs

标签: c arrays loops


【解决方案1】:

你的程序应该是这样的

#include <stdio.h>

int main(void)
{
    int n;
    printf("Enter the size of array: ");
    scanf("%d",&n);
    int array[n];           // Here it should be "n" not "n-1"

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

    int product = 0;

    for(int i=0; i<n; i++)
    {
        if(i>(n-1-i))
        {
            break;
        }
        int f = array[i];
        int l = array[n-i-1];       // Here it should be n-i-1

        product = product + (f*l);
    }
    printf("Result: %d\n",product);
    return 0;
}

【讨论】:

  • 相当不错。最好检查每个 scanf() 调用以确保它得到预期的结果(它应该每次返回 1;如果没有问题,是时候退出这个程序了)。跨度>
猜你喜欢
  • 2023-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-15
  • 2022-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多