要在main函数之外定义数组

问题:遇到了一个算法题,示例代码在main函数之外定义了数组,我试了在main函数之内定义数组,结果运行结果出错。
百度之后,网友对此解释说法不一,在我没搞懂这个问题之前,尽量在main函数之外定义数组

main函数之外定义数组:

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

struct Poly
{
	int exp;
	double coe;
}Poly[1001];//第一个数组

double ans[2001];//外部定义数组

int main()
{
	int n;
	scanf_s("%d", &n);
	for (int  i = 0; i < n; i++)
	{
		scanf_s("%d%lf", &Poly[i].exp, &Poly[i].coe);
	}

	//double ans[2001];//内部定义数组
	
	int m,number = 0;
	scanf_s("%d", &m);
	for (int i = 0; i < m; i++)
	{
		int exp;
		double coe;
		scanf_s("%d%lf", &exp, &coe);

		for (int j = 0; j < n; j++)
		{
			ans[exp + Poly[j].exp] += (coe*Poly[j].coe);
		}
	}

	for (int i = 0; i <=2000 ; i++)
	{
		if (ans[i] != 0.0) number++;
	}

	printf("%d", number);
	for (int i = 2000; i>=0; i--)
	{
		if (ans[i] != 0.0)
		{
			printf(" %d %.1f", i, ans[i]);
		}

	}


	system("pause");


	return 0;
}

内部定义数组:

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

struct Poly
{
	int exp;
	double coe;
}Poly[1001];//第一个数组

//double ans[2001];//外部定义数组

int main()
{
	int n;
	scanf_s("%d", &n);
	for (int  i = 0; i < n; i++)
	{
		scanf_s("%d%lf", &Poly[i].exp, &Poly[i].coe);
	}

	double ans[2001];//内部定义数组
	
	int m,number = 0;
	scanf_s("%d", &m);
	for (int i = 0; i < m; i++)
	{
		int exp;
		double coe;
		scanf_s("%d%lf", &exp, &coe);

		for (int j = 0; j < n; j++)
		{
			ans[exp + Poly[j].exp] += (coe*Poly[j].coe);
		}
	}

	for (int i = 0; i <=2000 ; i++)
	{
		if (ans[i] != 0.0) number++;
	}

	printf("%d", number);
	for (int i = 2000; i>=0; i--)
	{
		if (ans[i] != 0.0)
		{
			printf(" %d %.1f", i, ans[i]);
		}

	}


	system("pause");


	return 0;
}

输入样例:
2 1 2.4 0 3.2
2 2 1.5 1 0.5

输出样例
3 3 3.6 2 6.0 1 1.6

©️2020 CSDN 皮肤主题: 游动-白 设计师:上身试试 返回首页