我有一个算法,它应该显示两个数组是否相似。它的作品,但我不知道什么大小应该是阵列。特定数组的大小
例如:
int a[10], i = 0, r = 0, n = 0;
printf("Enter the amount of numbers in arrays: ";
scanf("%d", &n);
printf("Enter the numbers of array: ";
for (i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
如果我为输入 “n” 的变量n = 11,程序停止在终点。我的问题是:我应该把对数组a [THAT_PLACE],以确保这一计划将与大多数硬件兼容(我听说,这也从内存中视)
@ UPDATE1什么号码:
我选择了一个alk's解决方案。但它仍然不起作用。这里是我的代码:
int main()
{
int i = 0, temp_a = 0, switch_a = 0, temp_b = 0, switch_b = 0, n = 0;
printf("Enter the amount of numbers in arrays: ");
scanf("%d", &n);
{
int a[n], b[n];
printf("Enter elements of first array: ");
for (i = 0; i < n; ++i)
{
scanf("%d", &a[i]);
}
printf("Enter elements of second array: ");
for (i = 0; i < n; ++i)
{
scanf("%d", &b[i]);
}
do
{
switch_a = 0;
for (i = 0; i < n - 1; i++)
{
if (a[i] > a[i + 1])
{
switch_a = switch_a + 1;
temp_a = a[i];
a[i] = a[i + 1];
a[i + 1] = temp_a;
}
}
} while (switch_a != 0);
//bubble sort
do
{
switch_b = 0;
for (i = 0; i < n - 1; i++)
{
if (b[i] > b[i + 1])
{
switch_b = switch_b + 1;
temp_b = b[i];
b[i] = b[i + 1];
b[i + 1] = temp_b;
}
}
} while (switch_b != 0);
//Cheks, if an arrays are the same.
for (i = 0; i < n; i++)
{
if (a[i] != b[i])
{
printf("This two arrays don't have the same elements.\n\n\n");
return 0;
}
}
printf("This two arrays have the same elements.\n\n\n");
}
return 0;
}
你能检查一下吗?我找不到有什么问题...
你想要一个变量长度阵列,幸运的是C99开始。在声明'int a [n];' –
“之前,请先阅读scanf行所需的元素数量......”该程序将与大多数硬件兼容“ - 不应该编写程序以使其适用于**问题**它是为了解决? – Olaf
如果添加'#include',更新后的代码似乎可以正常工作。问题是什么?此外,这听起来像一个新的问题,与旧的问题无关。如果您可以识别问题,可能会发布一个新问题? –