I'm pretty new to C and I was wondering if there was any way for me to print out the return of a function so that I can see if it's doing what I want it to.
int sum_arr1_ok() {
int pass = 1;
int fail = 0;
int arr1[] = {1,2,3,4,5}; // small positive values
int arr2[] = {10,-5,5,8,-2}; //mix of small positive and negative values
int arr3[] = {-100,90,-374,497,64,-5,22}; // mix of larger positive negative values
int arr4[] = {0}; // zero
int arr5[] = {-2,-7,-19,-53,-5,-11}; // all negative values
int arr6[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20}; // large array
int n1 = sizeof(arr1)/sizeof(arr1[0]);
int n2 = sizeof(arr2)/sizeof(arr2[0]); //determines the number of elements in an array
int n3 = sizeof(arr3)/sizeof(arr3[0]);
int n4 = sizeof(arr4)/sizeof(arr4[0]);
int n5 = sizeof(arr5)/sizeof(arr5[0]);
int n6 = sizeof(arr6)/sizeof(arr6[0]);
if((sum_arr1(arr1,n1) == 15)
&& (sum_arr1(arr2,n2) == 16)
&& (sum_arr1(arr3,n3) == 194)
&& (sum_arr1(arr4,n4) == 0)
&& (sum_arr1(arr5,n5) == -97)
&& (sum_arr1(arr6,n6) == 210)) {
return pass; // returns 1 if true
} else {
return fail; // returns 0 if false
}
I know the if statements a little messy but right now I'm trying to find a way to see if my function is returning what I need it to properly.
How would I prepare a main function so that it prints out whether or not my tests passed or failed?
If you want to know what the function is returning, you need to refactor your code to save the return value in a variable so you can print it.
int rval;
rval = sum_arr1(arr1,n1);
printf("sum_arr1(arr1,n1) = %d\n", rval);
if (rval != 15) return false;
rval = sum_arr1(arr2,n2);
printf("sum_arr1(arr2,n2) = %d\n", rval);
if (rval != 16) return false;
rval = sum_arr1(arr3,n3);
printf("sum_arr1(arr3,n3) = %d\n", rval);
if (rval != 194) return false;
rval = sum_arr1(arr4,n4);
printf("sum_arr1(arr4,n4) = %d\n", rval);
if (rval != 0) return false;
rval = sum_arr1(arr5,n5);
printf("sum_arr1(arr5,n5) = %d\n", rval);
if (rval != -97) return false;
rval = sum_arr1(arr6,n6);
printf("sum_arr1(arr6,n6) = %d\n", rval);
if (rval != 210) return false;
return true;
Alternately, you can have the function print its parameters when it starts and its return value before it returns.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.