How to convert a double array to an integer array in C? - c

I have an array that is made up doubles which I need to round down and convert to integers so I can use them as indices in an output array. I have just started C programming and am not sure how this works. So far the best I have been able to come up with is:
int create_hist( double input_array[], int count, int output_array[17] ) {
for ( int i = 0; i < count; i++ ) {
input_array[i] = int floor(input_array[i]);
output_array[input_array[i]]++;
However I am getting the following errors which I am having trouble deciphering:
array.c:11:20: error: expected expression before ‘int’
input_array[i] = int floor(input_array[i]);
^
array.c:12:7: error: array subscript is not an integer
hist[input_array[i]]++;
^
array.c:14:1: error: control reaches end of non-void function [-Werror=return-type]
}
^
If someone could let me know where I have gone wrong it would be greatly appreciated.

Unless you actually want to modify input_array, you would be best off saving the rounded off double in an intermediate variable to then access your integer array. And no need to use floor() casting the double to int will do that.
int create_hist(double input_array[], int count, int output_array[17]) {
for (int i = 0; i < count; i++) {
int index = (int)input_array[i];
if ((index > 16) || (index < 0)) {
return -1;
}
output_array[index]++;
}
return 0;
}
Of course, you should really pass in the size of output_array as a variable as well, instead of hard-coding it.

So let get cracking:
First error is due to the fact that you are kind of declaring a function.
input_array[i] = int floor(input_array[i]);
notice int in front of floor, that is not necessary. It should be
input_array[i] = floor(input_array[i]);
Second error is due to the fact that you are accessing array element using double in
output_array[input_array[i]]++;
either you should do it some other way or do following:
output_array[(int) input_array[i]]++;
and the third error is unbalanced parenthesizes.

Related

Runtime error in my code

I was trying to implement this problem from SPOJ: http://www.spoj.com/problems/COINS/ using memoization but I keep getting Runtime error and cant figure out why. Here is my code:
#include<stdio.h>
long long int max(long long int a,long long int b)
{
if(a >= b)
return a;
else
return b;
}
long long int dp[100000];
long long solve(long long int n)
{
long long ans;
if(n<=50000)
return dp[n];
else
ans=(n,solve(n/2)+solve(n/3)+solve(n/4));
return ans;
}
int main()
{
long long int n;
int t;
for(int i = 0;i <=50000;i++)
{
dp[i] = max(i,dp[i/2] + dp[i/3] + dp[i/4]);
}
while((scanf("%d",&t))>0)
printf("%lld",solve(n));
return 0;
}
Here are a few problems:
In solve, you have ans = (n,solve(n/2)...); The leading n has no effect. Did you intend this to be an argument list to max? If so, you need to add max. Otherwise it's just a comma expression and you might as well remove the leading n.
In main, your initialization of dp has a problem. Consider the first pass through the loop, when i is 0. In this case, i/2 etc. will also be zero, hence those dp values will be undefined. Try setting dp[0] explicitly, outside of the loop, and then start your loop at index 1 instead.
When printing the solution in main, you probably want to add newling \n to the end of your printf format string.
As noted by others, when calling solve from main, you are passing n rather than t.
The problem is most likely due to this:
while((scanf("%d",&t))>0)
printf("%lld",solve(n));
You are reading t but passing n which is uninitialized. You probably want to pass t to solve():
while((scanf("%d",&t))>0)
printf("%lld",solve(t));
Reason you get Runtime Error
while((scanf("%d",&t))>0)
printf("%lld",solve(n));
Here, You get input in variable t but pass variable n to solve function. Use variable t or n for both case. It will solve your problem.

error: expected expression before ‘float’

I would like to find all the primes within 100. Here is my codes.
// Find all the prime number within 100.
#include<stdio.h>
#include<math.h>
#include<stdbool.h>
int main() {
int i,n;
int j = 0;
for ( n = 2; n <= 100; ++n) {
bool isPrime = true;
for (i = 2; i <= sqrt(float(n)); ++i) {
if(n % i == 0) {
isPrime = false;
break;
}
}
if(isPrime) {
++j;
printf("%d is a prime number\n",n);
}
}
printf("The total number of prime number within 100 is %d\n",j);
return 0;
}
When compile it, there is one error.
prime.c:14:8: error: expected expression before ‘float’
m = float(n);
^
Could anyone help solve this problem? Thanks.
You're using the wrong syntax when casting (you're using one of C++'s many styles of casting, but for C there is only one way). Change:
sqrt(float(n))
to
sqrt((float)n)
Note however that sqrt takes a double, so strictly speaking this should be:
sqrt((double)n)
Note also that the cast is not necessary, and you can just write:
sqrt(n)
Change this
sqrt(float(n))
to this
sqrt((float)n)
You want to cast n to float.
You should use this function:
float sqrtf (float x);
which in C99 receives a float as an argument. Otherwise, it would be better to cast into double (if you use sqrt()).
sqrt-ref
What you have written:
float(n)
is like saying that float is a name of a function and you pass to it the parameter n.
Notice, that in your case, you don't need casting, since it's going to be performed automatically (to float if you use sqrtf() or to double if you use sqrt()).
Other notes, irrelevant with your syntax error.
Why not start the loop from 3 and increase the counter by two? If you think about it, this will faster and will produce the same results. If you want to test yourself, check my example here.
Also, what I had found pretty exciting when I was searching for primes, is the sieve of Eratosthene's (Κόσκινο του Ερατοσθένη) . Here is an example of it.
If you want to cast n to a float, use (float)n.
Just do:
sqrt(n);
You'll be having the exam same result as the casting for your case.

Passing 2d arrays and then not getting a value

I am having an issue with some code that I am writing.
I use this site often as I have found many people who have already asked the same questions I am wondering. With that I want to thank the community on here for all of the previous insight into my programming conundrums.
(And before we get too far, no this is not a 'school project' or 'school homework', I am simply trying to solve the 'Travelling Salesman Problem' and better my C skills.
This is the portion of code I have been stuck on:
void printAndFlip(int arrayone[][20], int citytotal, int arrayCities[])
{
////Finds cost:
int x, y, z;
int totalCost
int singleTrip;
int cheepestTrip;
int nCity = citytotal + 1; //nCity is the number of Cities //Adding one to accomadate going back to the first city
int gCounter;
int gCounterTrue = 1;
int cheepestTrip[20];
int totalCost = 0;
int lCounter;
int i;
int n = citytotal;
////Sets up for a default case to set cheepestTrip:
for(gCounter = 1; gCounter <= nCity; gCounter++)
{
while(gCounterTrue == 1)
{
if(gCounter == arrayCities[gCounter])
{
gCounterTrue = 1;
}
else
{
gCounterTrue = 0;
gCounter = 50; //Stopping the larger for loop with 50 (the nCity can't be larger than 20) so that it will hopefully be faster
}
if(gCounter == nCity)
{
if(arrayCities[1] == arrayCities[nCity])
{
!!!!! cheepestTrip = totalCost;
}
}
}
}
for(x = 1; x < nCity; x++)
{
y = arrayCities[x];
z = arrayCities[x+1];
singleTrip = arrayone[y][z]; //finding individual cost of each trip...will be added to 'totalCost' below
totalCost = singleTrip + totalCost;
}
!!!!!!!! if(totalCost <= cheepestTrip)
{
for(lCounter = 1; lCounter <= nCity; lCounter++)
{
cheepestTrip[lCounter] = arrayCities[lCounter];
}
}
To make it easier to show where my compile errors are at I put exclamation points on the lines.
Please tell me if I am wrong, but I am passing an array of pointers with an array when I send 'arrayone' to printANDFlip right?
I know the compile errors are relating to the pointers but I am just uncertain of where they should be placed.
Any and all help will be appreciated.
Much thanks,
Alex
To make explicit what some of the other replies are saying: You have two variables with the same name but different types:
int cheepestTrip; /* This is an single integer... */
and
int cheepestTrip[20]; /* ...but this is an array of integers. */
This should be triggering a warning at compile time (probably something about redeclaring an existing variable).
Here you are comparing an array pointer with a int value
if(totalCost <= cheepestTrip)
For example you should compare it to an element of that array
if(totalCost <= cheepestTrip[0])
cheepestTrip is the name of the array, which is equivalent to a pointer to the first element. totalCost is an int. Just remove the [20] from your declaration at the top part of the code.
you are comparing a pointer to an int, which your particular compiler might not be allowing (though I though with C you could). but cheapestTrip is essentially a pointer to the first element in your array of ints, while totalcost is simply an int primative

Intersection function of two arrays in C

I am learning to use C in my operating systems class and this is what I have so far for my function to find the intersection of two arrays.
An intersection basically is when you take two sets and you get ONLY the elements that are in both sets.
So for example if set A contains = {1,2,3} and set B contains = {2,3,4} then the intersection of A and B are {2,3}. I'm trying to create a function in C that gets two arrays and returns an array containing integers that are in both passing arrays.
I think I almost have the solution here, but I'm getting an error that says:
"identifier 'count' is undefined"
int intersection(int array1[4], int array2[4])
{
int arrayReturn[sizeof(array1) + sizeof(array2)]
int count = 0;
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 4; j++)
{
if(array1[i]==array2[j])
{
count = count + 1;
arrayReturn[count] = array1[i];
}
}
}
}
I'm very used to Java and I feel like Java and C are nearly identical. I can't really find what's wrong here since count is well within its scope inside the if statement. I don't see how count is undefined.
What's wrong with count and how could I fix this intersection function?
You are missing a semi-colon in the line before count declaration.
int arrayReturn[sizeof(array1) + sizeof(array2)]; //Semicolon Here
int count = 0;
How did I see the error ?
The error message was identifier 'count' is undefined so the first thing I checked for is the cause that the compiler told me. That however was not the problem, as the declaration is there, and in the correct scope. So, now what should I do ? I should look at the line just before the initialization of the variable and at the line just before the usages. This is where you will most certainly find the error.
In short, when the compiler messages don't seem helpful, don't stop. Look around.
Also, as GRAYgoose124 points out, you should have a return statement at the end of your function body as your function is supposed to return an integer.
Missing a semi colon on this line:
int arrayReturn[sizeof(array1) + sizeof(array2)]; //semicolon was missing
As AshRj points out, you are missing a semicolon.
Tip: The clang compiler is excellent at giving diagnostic output. If you try to compile your code with it, you get the following output:
source.c:3:57: error: expected ';' at end of declaration
int arrayReturn[sizeof(array1) + sizeof(array2)]
^
;
Even if you're not compiling your project with clang normally, you can try to compile snippets to help you find out what's wrong. That's what I did with your snippet, as you can see here. (Note the warnings as well.)
void readArr(int arr1[],int n1, int arr2[],int n2,int arr3[]){
int n=0;
int j=0;
for(j=0;j<n1;j++){
for(int k=0; k<n2;k++){
if(arr1[j]==arr2[k]){
int element = arr1[j];
int k=checkArrayContains(arr3,n,element);
if(k==1){
printf("%d\n",arr1[j] );
arr3[n]=arr1[j];
n++;
}
}
}
}
displayArray(arr3,n);}
I think this implementation is more clear.

Syntax error while copying an multidimensional array to another in C

We are programming a ST269 microcontroller which has two IR distance sensors. To calibrate these sensors we made one table for each sensor with the distance we measured and the corresponding value we get from the ADC.
Now we want to use one function to approximate the values in between. So we defined two two-dimensional arrays (one for each sensor) as global variables. In our function we then want to copy the one array we want to work with to a working array and approximate our values.
So here's the code:
...
unsigned int ir_werte_re[][] = {
{8,553},
...
{83,133}
};
unsigned int ir_werte_li[][] = {
{8,566},
...
{83,147}
};
...
unsigned int geradenaproximation(unsigned int messwert, unsigned int seite)
{
unsigned int working_array[16][16];
unsigned int i = 0;
if (seite == 0) {
for (i = 0; i < sizeof(working_array); i++) {
working_array[i][0] = ir_werte_li[i][0];
i++;
}
}
else {
for (i = 0; i < sizeof(working_array); i++) {
working_array[i][0] = ir_werte_re[i][0];
i++;
}
}
i = 0;
unsigned int y1 = 0;
unsigned int x1 = 0;
...
}
This code is in a file called sensor.c. We didn't write anything about our global arrays in the sensor.h should we? The sensor.h of course is included in our main.c and there the function is called.
We also tried to copy the arrays via
memcpy(working_array, ir_werte_li, sizeof(working_array));
And in every way we do this we get a
syntax error near unsigned
in the line where we're declaring
unsigned int y1 = 0;
and I'm pretty sure that there is no syntax error in this line : )
The last time I spend coding in C is a few years away so I'm not sure if the way we try to do this is good. Perhaps we can solve this by using a pointer instead of really copying the array or something. So please help me out I'll appreciate your bits on this.
In C (pre-C99), all variable definitions must appear at the top of the current block scope.

Resources