c - C 中的 Malloc 和锯齿状数组
问题描述
我编写了一个打印二项式系数金字塔的程序。问题是当我使用 Xcode 编译和运行代码时它会正确打印它们,但是当我在终端中这样做时它会打印错误的数字。我希望有人能告诉我为什么会这样。我在 macOS Mojave 上运行最新版本的 Xcode。
更新:重新启动 Xcode 后,我也没有得到 Xcode 上系数的正确数字。
这是代码:
#include <stdio.h>
#include <stdlib.h>
/* Function prototype */
int C(int a, int b);
int main(){
int count =0;
int n = 0; /* The number of rows in the array (minus 1) */
/* Prompt user to input and validate */
printf("Please enter a positive integer:\n"
"n = ");
do
scanf("%d", &n);
while ( n <= 0 );
/* Allocate enough memory for the matrix */
int **matrix = (int**) malloc( (n+1) * sizeof(int*) );
/* Allocate enough memory for each array */
for (int i = 0; i < n+1; i++) {
matrix[i] = (int*) malloc( (i+1) * sizeof(int) );
}
/* Populate each array */
for (int i = 0; i < n+1; ++i) {
for (int j = 0; j < i+1; ++j) {
matrix[i][j] = count;
count++;
}
}
/* Print pyramid */
for (int i = 0; i < n+1; ++i) {
for (int j = 0; j < i+1; ++j) {
if ( (i==0) && (j==0) ) {
for (int k = 0; k < n+1-i; ++k) {
printf("\t");
}
printf("%d\n", matrix[i][j]);
}
else
if (j == 0) {
for (int k = 0; k < n+1-i; ++k) {
printf("\t");
} printf("%d\t", matrix[i][j]);
} else
if ( (0 < j) && (j < i) ) {
printf("\t%d\t", matrix[i][j]);
}
else
if (j == i) {
printf("\t%d\n", matrix[i][j]);
}
}
}
/* Free allocated memory */
free(matrix);
return 0;
}
/************************ Function Definition **********************/
/*
* Function: C
* -----------
* Computes the binomial coefficient via the factorial formula, using
* for-loops for the factorials.
*
* f_a = the factorial of the first number
* f_b = the factorial of the other number
* f_a_b = the factorial of the difference (a-b)
*
* returns: the binomial C = (a,b)
*/
int C(int a, int b) {
unsigned int f_a = 1;
unsigned int f_b = 1;
unsigned int f_a_b = 1;
for ( int i = 1; i < a; ++i ) {
f_a *= i;
}
for ( int i = 1; i < b; ++i ) {
f_b *= i;
}
for ( int i = 1; i < (a-b); ++i ) {
f_a_b *= i;
}
unsigned int C = f_a / ( f_b * f_a_b );
return C;
}
解决方案
您计算阶乘的方式是错误的:
for ( int i = 1; i < a; ++i )
应该
for ( int i = 1; i <= a; ++i )
因为你必须包括最后一个元素。这就是定义阶乘的方式。
此外,此函数更适合计算二项式系数,因为阶乘在13
(使用 32 位 int 时)溢出。
int C(int a, int b)
{
int bc = 1;
if (b > a-b)
{
b = a-b;
}
for (int i = 0; i < b; i++)
{
bc *= (a - i);
bc /= (i + 1);
}
return bc;
}
推荐阅读
- javascript - 如何同步获取多个文件并将它们加载到单个变量中
- google-cloud-platform - 代码无法使用 DML 更新 BQ 上的表,但使用 RPC 插入和删除成功
- function - 我可以在 Rust 中声明函数并稍后在 C++ 中定义它吗?
- java - 后台年轻并发复制GC - JAVA
- javascript - JavaScript数组改组-为什么必须将随机数向下移动0.5到负范围?
- scala - 如何使用 Scala 访问 Spark DataFrame 每个单元格的最后两个字符以对其值进行一些计算
- python - 使用两个下拉按钮构建一个散点图,一个用于 x 轴,一个用于 y 轴
- vim - 在 Vim 中,数字键盘上的 5 键在当前行上方插入一行,并带有 "E"
- dart - 将枚举的值反映为类的值
- react-native - 在 redux 商店中保存多个图像是一种好习惯吗?