我正在编写一项作业(job),要求我做以下工作:

1. User input:十进制数字列表.(这些项目代表美元的数值,第一项是美元兑换比率,

(比方说1usd = 3.58another_currency个.)

  1. 将值转换为另一种货币(转换后的项目将以another list为单位)

2.1例如: 原文:[3.58 12 11.50 3.20 4.10] -> 转换:[(42.96),(41.17),.] (multiplied 3.58 by each item next)

  1. 以漂亮的表格形式显示它,表格的最后一行应该是the sum of the dollarsthe sum of the converted currency

It seems that I have done the first step, and the second step correctly. But when calculating the sum of the other currency, I ran into a problem. Only the sum of the dollars happen to be correct, but the sum of the other currency is problematic. Not only it's incorrect, the sum is changing every time I run it. Green one is correct, red one is not correct. enter image description here

我激活了same function upon the two different arrays,但它只正确计算了其中的一个和.

MY .H文件(doll.c):

#define SIZE 10

void dollar_to_shekel(float[], float[]);

void print_array(float[], float[]);

float sum_array(int, float[]);

我的.c文件(doll.c):

#include <stdio.h>
#include "doll.h"

void dollar_to_shekel(float usd[], float ils[])
{
  int i;
  for(i=1; i<SIZE; i++)
  {
    /*the first element in the received list, in index 0, is the dollar ratio*/
    ils[i-1] = usd[i] * usd[0];
  }
}

void print_array(float usd[], float ils[])
{
  int i;
  for(i=1; i<SIZE; i++)
  {
    printf("%.2f \t \t \t \t %.2f\n", usd[i], ils[i-1]);
  }
}

float sum_array(int x, float arr[])
{
  int i;
  float sum = 0;
  for(i=x; i<SIZE; i++)
  {
    sum = sum + arr[i];
  }
  return sum;
}

int main()
{
  float usd[SIZE];
  float ils[SIZE];
  int i;
  printf("Insert a list of numbers:");
  for(i=0; i<SIZE; i++)
  {
    scanf("%f", &usd[i]);
  }

  dollar_to_shekel(usd, ils);
  printf("$ \t \t \t \t IS\n");
  print_array(usd,ils);
  printf("%.2f \t \t \t \t %.2f\n", sum_array(1,usd), sum_array(0,ils));

  return 0;
}

我真的不知道程序在哪里以及为什么在计算一列的总和时失败,但在另一列上做了这项工作.

推荐答案

正如在dollar_to_shekel中的循环中,在最后一次迭代中,您分配了ils[SIZE-1-1],这是正确的,因为您从0开始并且有SIZE-1值要计算,您没有分配ils[SIZE-1],但它包含在sum_array中的sum中.ils[SIZE-1]是一个"随机"值,所以求和的结果也是随机的. 一个解决方案是求和直到SIZE-x:

    float sum_array(int x, float arr[])
    {
      int i;
      float sum = 0;
      for(i=x; i<SIZE-x; i++)
      {
        sum = sum + arr[i];
      }
      return sum;
    }

C++相关问答推荐

生成C代码时自动复制/生成' tmwtypes.h '依赖项

数组元素的编号索引

如何在不修改字符串缓冲区早期使用的情况下覆盖字符串缓冲区

Mbed TLS:OAEP的就地en—/decryption似乎不起作用'

当main函数调用被重构时,C函数给出错误的结果

为什么net/if.h在ifaddrs.h之前?

等同于铁 rust 的纯C语言S未实现!()宏

在libwget中启用Cookie会导致分段故障

S和查尔有什么不同[1]?

将数组插入数组

如何将C中的两个字符串与从文件接收的字符串中的字符数进行比较

正在try 理解C++中的`正在释放的指针未被分配‘错误

在文件描述符上设置FD_CLOEXEC与将其传递给POSIX_SPOWN_FILE_ACTIONS_ADCLOSE有区别吗?

`%%的sscanf无法按预期工作

C中2个数字的加法 - 简单的人类方法

If语句默认为true

C循环条件内的函数

memcmp 是否保证按顺序比较字节?

C23 中的 [[reproducible]] 和 [[unsequenced]] 属性是什么?什么时候应该使用它们?

C23 中是否有 __attribute__((nonnull)) 的等效项?