我主要是一名 Python/MIT Scheme 程序员,但我想学习 C,因为我将在下学期学习 C,我想做好准备。我会说我对python和scheme非常好,所以我不是一般编程的新手。这是我的一个爱好:)。
所以我尝试编写一个 C 程序来计算帕斯卡三角形,但它给了我一个不正确的输出。我编译没有错误,这是我的代码:
/*
This code is just to see exactly how much faster C is than python
at doing numerically stuff. It should calculate the nth row of
pascals triangle.
The way you use it is by calling the executable with the row
you wish to compute as the only argument. For example if you
are on an *nix system:
./pascal 6
Or in a windows command prompt:
pascal.exe 6
*/
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
/*
I decided to use a struct here because I thought it was ugly
to have to pass around the length of my arrays in function
calls.
*/
typedef struct{
int length;
unsigned long int* vals;
} CoolArray;
//initArray allocates memory for the CoolArray.
void initArray(CoolArray* array, int length);
//destroyArray frees allocated memory in the struct.
void destroyArray(CoolArray* array);
//printArray prints the contents of the array.
void printArray(CoolArray* array);
//pascal computes the nth row of pascal's
//triangle, with n being array->length,
//and stores the values in the array.
void pascal(CoolArray* array);
//setArray takes two CoolArrays of the same length
//and sets the values in the first to the values
//in the second.
void setArray(CoolArray* array1, CoolArray* array2);
int main(int argc, char** argv){
int length = atoi(argv[1]);
CoolArray array1;
initArray(&array1, length);
printf("Calculating the %dth row of pascals triangle...\n", length);
pascal(&array1);
printArray(&array1);
destroyArray(&array1);
return 0;
}
void initArray(CoolArray* array, int length){
assert(length>=1); //don't make arrays with a length <=0!!!
array->length = length;
array->vals = (unsigned long int*) calloc(length, sizeof(unsigned long int));
return;
}
void destroyArray(CoolArray* array){
free(array->vals);
return;
}
void pascal(CoolArray* array){
assert(array->length >= 1);//making sure the length wasn't fiddled with...
if(array->length == 1){
array->vals[0] = 1;
return;
}
int row;
int index;
array->vals[0]=1; //if we aren't looking for the first row
array->vals[1]=1;//then i'll start with the second row
CoolArray current;
initArray(¤t, array->length);
for(row = 2; row < array->length; ++row){
current.vals[0]=1;
for(index = 1; index < row; ++index){
current.vals[index]=array->vals[index]+array->vals[index-1];
}
current.vals[row]=1;
printArray(¤t);
setArray(array, ¤t);
}
destroyArray(¤t);
return;
}
void setArray(CoolArray* array1, CoolArray* array2){
assert(array1->length==array2->length);//making sure they are the same length
int i=0;
for(; i < array2->length; ++i){
array1->vals[i]=array2->vals[i];
}
return;
}
void printArray(CoolArray* array){
int i=0;
printf("[");
for(; i < array->length; ++i){
if (i = array->length - 1) printf("%d]\n", array->vals[i]);
else printf("%d, ", array->vals[i]);
}
return;
}
谁能看到我哪里出错了?它的输出现在看起来像这样:
./帕斯卡 6
计算帕斯卡三角形的第 6 行...
[1]