纯粹贴代码,使用VLA创建和计算任意二维数组的值的和

七月底去开个GayHub

/* 通过VLA计算多维数组所有数值的和 */
#define BUFSIZE 500
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
void chartrim(char cache[],int length);
double sumdarray(int rows,int cols,double array[rows][cols]);
int main(void)
{
  char cache[BUFSIZE];
  int rows,cols;
  printf("How many rows does your array have?\n");
  gets(cache);
  rows = atoi(cache);
  chartrim(cache,BUFSIZE);
  printf("How many columns does your array have?\n");
  gets(cache);
  cols = atoi(cache);
  chartrim(cache,BUFSIZE);
  double array[rows][cols];
  for(int i=0;i<rows;++i)
  {
    for(int n=0;n<cols;++n)
    {
      printf("Enter the data at position %d * %d in your array\n",i+1,n+1);
      gets(cache);
      array[i][n] = atoi(cache);
      chartrim(cache,BUFSIZE);
    }
  }
  printf("The total sum of your array is : %lf\n",sumdarray(rows,cols,array));
  return 0;
}
void chartrim(char string[],int length)
{
  for(int n=0;n<length;++n)
  {
    string[n] = 0;
  }
}
double sumdarray(int rows,int cols,double array[rows][cols])
{
  double result;
  result = 0;
  for(int i=0;i<rows;++i)
  {
    for(int n=0;n<cols;++n)
    {
      result += array[i][n];
    }
  }
  return result;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容