C/C++

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

2017-07-10  本文已影响0人  Dumbass

七月底去开个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;
}
上一篇 下一篇

猜你喜欢

热点阅读