I'm finishing a program that I found in my C book but I ran into some issues.
I'm just about done but I keep getting this error
Error 1 error C2440: 'function' : cannot convert from 'double [15]' to '
Why am i getting this compiler error?
void arrayRead(double, int*);
void arrayList(double, int*);
void arraySum(double, int*, int*);
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<ctype.h>
int main()
{
int num, sum = 0;
double array[15];
printf("How many doubles (numbers) would you like in the array (20 max)?\n");
scanf("%d", &num);
printf("Thank you! Now give me %d different doubles (numbers) please!\n", num);
arrayRead(array, &num);
printf("Here are all of your integers again!\n");
arrayList(array, &num);
arraySum(array, &num, &sum);
printf("The sum of these numbers = %d\n", sum);
return 0;
}
void arrayRead(double array[], int* num)
{
for (int i = 0; i < *num; i++)
{
scanf("%lf", &array);
}
}
void arrayList(double array[], int*num)
{
for (int i = 0; i < *num; i++)
{
printf("%.2f\n", array);
}
}
void arraySum(double array[], int*num, int* sum)
{
for (int i = 0; i < *num; i++)
{
*sum = array + *sum;
}
}
best to place prototypes after any #include statements,
just in case the prototype uses something defined in the header file
The size of the array must be a positive number,
so use '%u' to input a positive numbe
and define the max variable as unsigned
The parameters to functions and the parameters passed when calling those functions need to have matching types (or the function type be a 'promotion' of the passed type.
since the array is doubles, all the references should also be double, like the sum variable.
appropriate horizontal white space makes the code much easier to read
do not #include header files those contents are not being used.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
//#include <ctype.h>
// prototypes
void arrayRead( double*, unsigned );
void arrayList( double*, unsigned );
void arraySum ( double*, unsigned, double* );
int main( void )
{
unsigned num;
double sum = 0.0;
printf( "How many doubles (numbers) would you like in the array (20 max)?\n" );
if( 1 != scanf( "%u", &num ) )
{
perror( "scanf for size of array failed" );
exit( EXIT_FAILURE );
}
// implied else, scanf successful
// need to add check that user entered value is in range 1...20
double array[ num ];
printf( "Thank you! Now give me %u different doubles (numbers) please!\n", num );
arrayRead( array, num );
printf( "Here are all of your integers again!\n" );
arrayList( array, num );
arraySum( array, num, &sum );
printf("The sum of these numbers = %lf\n", sum);
return 0;
} // end function: main
void arrayRead( double array[], unsigned num )
{
for ( unsigned i = 0; i < num; i++ )
{
scanf("%lf", &array[i]);
}
} // end function: arrayRead
void arrayList( double array[], unsigned num )
{
for ( unsigned i = 0; i < num; i++ )
{
printf("%.2f\n", array[i]);
}
} // end function: arrayList
void arraySum( double array[], unsigned num, double* sum )
{
for ( unsigned i = 0; i < num; i++ )
{
*sum = array[i] + *sum;
}
} // end function: arraySum
Here is the output from a simple run of the answer code:
How many doubles (numbers) would you like in the array (20 max)?
5
Thank you! Now give me 5 different doubles (numbers) please!
1 1 1 1 1
Here are all of your integers again!
1.00
1.00
1.00
1.00
1.00
The sum of these numbers = 5.000000
The functions you have declared have different signatures than the functions you have defined.
Be careful in the declaration you use double instead of double *. It is not the same.
When you call the arrayRead function and company, the compiler sees only the declared functions as the defined functions are after the calls. So the parameters doesn't match.
By the way, in the defined functions you forgot to write the index. You are using the pointer and this can't work. You need to write array[i] inside each loop.
Related
This is the question "Write a function which gets an integer array and number of elements as parameters and calculates and displays sum and average of all the integers of the array in C language"
Below is the code which I have done, it's running but consists of bugs which give false answers
#include <stdio.h>
void SumAvg(int x, int arr[x]) {
int i, sum = 0;
float avg = 0;
for (i = 0; i < x; ++i) {
sum += arr[i];
}
avg = (float)sum / x;
printf("The sum is %d", sum);
printf("\nThe average is %.2f", avg);
}
int main() {
int x, i;
printf("Enter number of elements");
scanf("%d", &x);
int arr[x];
for (i = 0; i < x; ++i) {
printf("Enter integers for array[%d]", i + 1);
scanf("%d", &arr[i]);
}
SumAvg(x, arr[x]);
return 0;
}
First , your function calling is wrong .It should be SumAvg(x,arr) instead of SumAvg(x, arr[x]);.
also in function declaration , in some compiler void SumAvg(int x, int arr[x]) might be problematic.
For starters the function should be declared the following way
void SumAvg( const int arr[], size_t n );
That is the parameter that declares the array shall have the qualifier const because the array is not changed in the function.
The number of elements of the array should have the type size_t.
The function definition can look the following way
void SumAvg( const int arr[], size_t n )
{
long long int sum = 0;
for ( size_t i = 0; i < n; i++ )
{
sum += arr[i];
}
double avg = n == 0 ? 0 : ( double )sum / n;
printf( "The sum is %lld\n", sum );
printf( "The average is %.2f\n", avg );
}
That is within the function the variable sum should have the type long long int to decrease the risk of overflow.
In general the user can pass to the function the number of elements equal to 0. In this case if not to check this value the function will have undefined behavior.
This call of the function
SumAvg(x, arr[x]);
is invalid because instead of passing the array you are passing its non-existent element with the index x.
Taking into account the provided function definition above a valid call of the function will look like
SumAvg( arr, x );
I am trying to test this method (call by value) i recently learned, but for unkown reasons for me, the code isn't working, can someone explain me why? (sorry for the mess by the way)
#include <stdio.h>
#include <stdlib.h>
void fact(int i);
int main() {
int x;
scanf("%d", x);
//function called:
fact(x);
printf("value of x! = %d", x);
return 0;
}
//factorial definition:
void fact(int i){
int j=0;
for(i=1; j>1; j--){
i= i * j;
return;
}
}
If you are using a call to a function by value to make calculations with the passed argument then to get the result of the calculations in the caller the function must return a value. That is its return type should not be void.
The definition of the function fact does not make sense. In the for loop the parameter i is reassigned to 1. The loop itself never iterates because another variable j is set to 0. So it can not be greater than 1.
int j=0;
for(i=1; j>1; j--){
The function can be defined the following way
//factorial definition:
unsigned long long int fact( unsigned int i )
{
unsigned long long int f = 1;
while ( i > 1 ) f *= i--;
return f;
}
The factorial is defined for unsigned natural integers.
In main you need to declare a variable of the type unsigned int like
unsigned int x;
This call of scanf
scanf("%d", x);
is incorrect. The function needs to accept its integer argument by reference to change it.
scanf( "%u", &x );
To get the result of the function fact you have to introduce one more variable
unsigned long long int result = fact( x );
And to output it you should write
printf( "value of %u! = %llu\n", x, result );
Here is a demonstrative program.
#include <stdio.h>
unsigned long long int fact( unsigned int );
int main(void)
{
unsigned int x;
scanf( "%u", &x );
unsigned long long int result = fact( x );
printf( "value of %u! = %llu\n", x, result );
return 0;
}
//factorial definition:
unsigned long long int fact( unsigned int i )
{
unsigned long long int f = 1;
while ( i > 1 ) f *= i--;
return f;
}
If to enter the number 20 then the function output will be
value of 20! = 2432902008176640000
Pay attention to that 20 is the maximum number the factorial of which can be stored in an object of the type unsigned long long int.
If you want that the function accepted its argument by reference and returned the result in the argument then you have to declare the variable x as having the type unsigned long long int.
Here is a demonstrative program.
#include <stdio.h>
void fact( unsigned long long int * );
int main(void)
{
unsigned long long int x;
scanf( "%llu", &x );
printf( "value of %llu! = ", x );
fact( &x );
printf( "%llu\n", x );
return 0;
}
//factorial definition:
void fact( unsigned long long int *x )
{
unsigned long long int f = 1;
while ( *x > 1 ) f *= ( *x )--;
*x = f;
}
If to enter 20 then the program output will be the same as shown above.
value of 20! = 2432902008176640000
Scanf takes a pointer to the variable, to return something from a void function you must call it by reference with a pointer to the return variable and not by its value.
Problem 1:
scanf("%d", x);
Should be:
scanf("%d", &x);
The & is very important.
Problem 2
In function fact, you start j at 0:
int j=0;
Your loop only runs while j>1:
for(i=1; j>1; j--){
Tell me: When is 0 ever >1??
Your loop will never run.
Problem 3:
You expect that calling fact(x); will change the value of x.
In C, a function cannot change one of its arguments; arguments are passed "by-copy".
If you wish to change an object (variable) in the caller, you must pass a pointer to it:
void fact(int* i);
[...]
//function called:
fact(&x);
[...]
//factorial definition:
void fact(int* i){
int j=0;
for(*i=1; j>1; j--){
*i= *i * j;
return;
}
}
#include <stdio.h>
main()
{
int num[9], i = 0, count = 0;
while (i<10)
{
scanf("%d", &num[i]);
if (num[i] % 2 == 0)
{
count++;
}
i++;
}
printf("we have %d double numbers\n", count);
}
Run-Time Check Failure #2 - Stack around the variable was corrupted
What should I do?
Your while loop hits all values of i from 0 to 9 inclusive, but attempting to access num[9] takes you out of bounds. You'll need to reduce the while loop range:
while (i<9) {
...
}
In addition, you really should give your main() function a return type, since modern compilers don't tolerate it being missing:
int main()
{
...
return 0;
}
The valid range of indices that can be used to access an array with N elements is [0, N - 1] or that is the same [0, N ).
Thus the condition in the while statement
while (i<10)
has to be rewritten like
while (i < 9)
The reason of the error is using "magic numbers" throughout the program.
Try to use named constants instead of magic numbers, In this case it will be easy to understand what magic number is used in what part of the code.
The program can look like
#include <stdio.h>
#define N 9
int main( void )
{
int num[N];
unsigned int count = 0;
unsigned int i = 0;
while ( i < N )
{
scanf( "%d", &num[i] );
if ( num[i] % 2 == 0 ) ++count;
i++;
}
printf( "we have %u double numbers\n", count);
}
Instead of the while loop it would be better to use a for-loop because the variable i is not used outside the loop.
For example
#include <stdio.h>
#define N 9
int main( void )
{
int num[N];
unsigned int count = 0;
for ( unsigned int i = 0; i < N; i++ )
{
scanf( "%d", &num[i] );
if ( num[i] % 2 == 0 ) ++count;
}
printf( "we have %u double numbers\n", count);
}
A more correct approach of declaring indices of arrays is using the type size_t for them.
In fact the array is not used in the program. You could count even entered values without using an array.
Take into account that according to the C Standard the function main without parameters shall be declared like
int main( void )
I am trying to solve problem 1A on codeforces
but i keep getting Test: #1, time: 0 ms., memory: 1828 KB, exit code: 1, checker exit code: 0, verdict: RUNTIME_ERROR
you can check my entry here and find my code below , i tried to to run the program locally and it works fine and it passed the test case on the website
#include<stdio.h>
int calculateSquare(int n , int m , int a){
int length=0;
int width = 0;
if(n%a != 0){
length = (n/a)+1 ;
}
else{
length = n/a ;
}
if(m%a != 0){
width = (m/a)+1 ;
}
else{
width = m/a ;
}
return length*width ;
}
void main(){
int n,m,a ;
scanf("%d %d %d",&n,&m,&a);
int output = calculateSquare(n,m,a);
printf("%d",output);
}
int calculateSquare(int n , int m , int a)
return type is int and return value is length*width
In the worst case a would be 1 and n, m would be 109 as stated in the problem
Input
The input contains three positive integer numbers in the first
line: n, m and a (1 ≤ n, m, a ≤ 109).
So the return type int cannot hold the returned value for such case.
Better using long long int if the compilation is conform with C99 standard.
I modified your code as given below which seems to be working fine :
#include <stdio.h>
long long int calculateSquare(long n , long m , long a){
long length=0;
long width = 0;
if(n%a != 0){
length = (n/a)+1 ;
}
else{
length = n/a ;
}
if(m%a != 0){
width = (m/a)+1 ;
}
else{
width = m/a ;
}
long long store = length*widthl
return store;
}
int main(){
long int n,m,a ;
scanf("%ld %ld %ld", &n, &m, &a);
long int output = calculateSquare(n,m,a);
printf("%ld\n", output);
return 0;
}
when trying to 'beat the clock', it is best to not use 'expensive' I.O functions.
Suggest the following two functions:
#include <stdio.h>
void fastRead( size_t *a );
void fastWrite( size_t a );
inline void fastRead(size_t *a)
{
int c=0;
// note: 32 is space character
while (c<33) c=getchar_unlocked();
// initialize result value
*a=0;
// punctuation parens, etc are show stoppers
while (c>47 && c<58)
{
*a = (*a)*10 + (size_t)(c-48);
c=getchar_unlocked();
}
//printf( "%s, value: %lu\n", __func__, *a );
} // end function: fastRead
inline void fastWrite(size_t a)
{
char snum[20];
//printf( "%s, %lu\n", __func__, a );
int i=0;
do
{
// 48 is numeric character 0
snum[i++] = (char)((a%10)+(size_t)48);
a=a/10;
}while(a>0);
i=i-1; // correction for overincrement from prior 'while' loop
while(i>=0)
{
putchar_unlocked(snum[i--]);
}
putchar_unlocked('\n');
} // end function: fastWrite
This occurs when an uninitialized variable is passed as an Array or Vector size.
Code with error:
int m;
vector<int> arr(m);
//throws Exit code 2147483647
//default value of uninitialized int variable is 4201296 > 10^5
//so the vector<int> can't be created.
Correct answer:
int m;
cin>>m; //this works
vector<int> arr(m);
can someone please help me figure out what i'm doing wrong here? i'm getting inaccurate results here. I seem to be getting the first value in the array each time and i cant seem to figure out what i'm doing incorrectly
#include <stdio.h>
int getbillsum ( int price[] );
int main( void )
{
int itemprice [10];
int total = 0;
for (int c=0;c <10;c++ ) //Looping to get item prices
{
printf ("\nEnter the price of the item: ");
scanf (" %d", &itemprice[c]);
}
total = getbillsum (itemprice);
printf ("%d", total);
return 0;
}
int getbillsum (int price []) //function to sum the values in array
{
int sum = 0;
for (int i=0; i<sizeof(price); i++)
{
sum+=price[i];
}
return sum;
}
You can't pass arrays to functions in C (well, not as an array anyway). Arrays decay into pointers, the sizeof which is always the same (4 for 32 bit systems, 8 for 64 bits).
For more information see paragraph 2.3 here.
The easiest, most common and most reliable way of solving your issue is to pass the length of the array as a second argument:
int getbillsum (int *price, size_t len)
{
int sum = 0;
for (int i=0; i<len; ++i)
sum += price[i];
return sum;
}
//usage
int main ( void )
{
int price[10];
for(int i=0;i<10;++i)
scanf(" %d", &price[i]);
printf("Sum: %d\n", getbillsum(price, sizeof(price)/sizeof(*price)));
return 0;
}
You also had a problem in your code: you added the return statement inside of your loop.
Just a quick-tip: The sum of an array of ints is not unlikely to be too much for a single int to hold, so I'd change the return-type of getbillsum to long, too
I've also edited your question, addressing quite a lot of issues considering how short your code was:
int getbillsum ( price );//missing type, changed to
int getbillsum ( int price[] );//better would be int getbillsum ( int *price ); but considering your question, left it as array
scanf ("%d", &itemprice[c]);//unsafe, changed it to
scanf (" %d", &itemprice[c]);//add space
total = getbillsum (itemprice,9);//why the second param?
total = getbillsum (itemprice);//to match function prototype
return sum;//moved OUTSIDE of the loop...
sizeof(price) does not give you the length of the array, but the size of the pointer (int price[]), which is probably 4. Also, you immediately return in the first for run. Put return outside the for loop.
You do fix it by supplying the array size, but you never use it. Update your getbillsum function:
int getbillsum (int price [], int length) //function to sum the values in array
{
int sum = 0;
for (int i=0; i<length; i++)
{
sum+=price[i];
}
return sum;
}
In addition to posted answers, you can consider a technique suggested in this answer.
Edit Quoted from comment
it's non-standard, dangerous (think of overflow, forgetting to
dereference at the correct offset and the like), and you should not
try this
In your case it will be something like that :
void *p = calloc(sizeof(itemprice) + sizeof(unsigned long int),1));
*((unsigned long int*)p) = 10;
quote from linked answer
n is now stored at ((unsigned long int)p)
Your getbillsum will look like that now (did not compile it, consider it as pseudocode)
int getbillsum (void* p)
{
int* price = p+sizeof(unsigned long int);
unsigned long int size = *p;
int sum = 0;
for (int i=0; i<size; i++)
{
sum+=price[i];
}
return sum;
}