| Thread Closed |
Why does this code not do what it should |
Share Thread | Thread Tools |
| Nov17-07, 01:33 PM | #1 |
|
|
Why does this code not do what it should
I can't see what is wrong with this code, but for some reason it doesn't work. It compiles, just doesn't do what it should.
Code:
for(i=0; i<n; i++)
{
delx[i] = i/n;
}
|
| PhysOrg.com |
science news on PhysOrg.com >> Hong Kong launches first electric taxis >> Morocco to harness the wind in energy hunt >> Galaxy's Ring of Fire |
| Nov17-07, 02:00 PM | #2 |
|
|
If i is declared type int, and n is declared type int, that would explain the behavior.
try this: delx[i] = float(i)/float(n); this is called casting, when you force the the type of a variable to change for a particular calculation (I am not sure if float() is the correct syntax for C). Alternatively I think you can declare n as a float, but I am no C expert. The problem though is that when you divide a small integer by a large one and get an integer result, the result has to be zero. |
| Nov17-07, 02:02 PM | #3 |
|
Recognitions:
|
Presumably i and n are integers? Integer division will round down.
Use delx[x] = (float)i/(float)n; |
| Nov17-07, 02:12 PM | #4 |
|
|
Why does this code not do what it should
The problem seems to be that you're not casting correctly (assuming array type int). The way I would do it is to make my array a float and then do a integer division and perform casting:
Code:
#include <stdio.h>
#define n 10
int main()
{
float delx[n];
int i=0;
for(i=0; i<n; i++)
{
delx[i] = (float) i/n;
printf("%f\n", delx[i]);
}
return 0;
}
|
| Nov17-07, 03:43 PM | #5 |
|
Recognitions:
|
The code in the op doesn't define i or n, or say if n is the array size;
Some (naughty) compilers will cast a float index to an array to int. |
| Nov18-07, 11:19 AM | #6 |
|
|
|
| Nov18-07, 01:23 PM | #7 |
|
Recognitions:
|
|
| Thread Closed |
| Thread Tools | |
Similar Threads for: Why does this code not do what it should
|
||||
| Thread | Forum | Replies | ||
| Convert latex code to fortran code? | Math & Science Software | 1 | ||
| C++ Code Help | Programming & Comp Sci | 3 | ||
| plz tell me wat this code is doing? | Programming & Comp Sci | 0 | ||
| Code | Brain Teasers | 0 | ||
| [img] code | Forum Feedback & Announcements | 3 | ||