cant get this to compile is there any way to do this
#include %26lt;iostream.h%26gt;
int main()
{
int count[9],n,i;
// sets number of sales user will enter
cout %26lt;%26lt; "/n Please enter how many salaries you would like to enter: ";
cin %26gt;%26gt; n;
int *n_ptr = %26amp;n; /sets pointer for memeory allocation
// gets sale input from customer
double sales[n_ptr];
for (i= 0; i %26gt; n; ++i)
{
cout %26lt;%26lt; "/n/n Please enter sales totel " %26lt;%26lt; endl;
cin %26gt;%26gt; sales[i];
}
// computes salaries
n = 1;
int saleries[n_ptr];
for (i=0 ; i %26gt; n; ++i)
{
int saleries[i] = 200 + sales[i]*.09;
}
return 0;
}
C++ problem arrays?
1) You coded: for (i= 0; i %26gt; n; ++i)
Should the condition be "i %26lt; n"? (And not "i %26gt; n")
2) You coded:
a) double sales[n_ptr];
b) int saleries[n_ptr];
Why are you declaring the arrays using an integer's address? Shouldn't you first de-reference the pointer, and then instead use the value that is stored at that address?
Instead, code should read:
a) double sales[*n_ptr];
b) int saleries[*n_ptr];
Reply:In your code problem starts here:
double sales[n_ptr];
Above statment is incorrect both syntactically %26amp; logically. First n_ptr is an memory address not an integer value(u could have replaced that with n or *n_ptr). Also, when u declare a static array, u have to use a fixed size say 100 etc.(e.g. sales[100])
Here size of sales array is not known at compile time so u will have to use dynamic memory allocation.
double * sales[n] =NULL; // Pointer , initialize to nothing.
sales = new double[n]; // Allocate n ints and save ptr in sales.
for (int i=0; i%26lt;n; i++) {
sales[i] = 0; // Use as an normal array.
}
. . . // Use as a normal array
delete [] sales; // When done, free memory
slaes = NULL; // Clear to prevent using invalid memory reference.
Also, correct this statement:
for (i= 0; i %26gt; n; ++i)
It should be i%26lt;n
Reply:#include %26lt;iostream%26gt;
using namespace std;
int main()
{
int n,i;
cout %26lt;%26lt; "Please enter how many salaries you would like to enter: ";
cin %26gt;%26gt; n;
double *sales = new double[n];
for (i=0; i%26lt;n; i++) {
cout %26lt;%26lt; "Please enter sales total: ";
cin %26gt;%26gt; sales[i];
}
// computes salaries
int *salaries = new int[n];
for (i=0; i%26lt;n; i++) {
salaries[i] = (int) (200. + sales[i] * .09);
}
// display
for (i=0; i%26lt;n; i++) {
cout %26lt;%26lt; "sale" %26lt;%26lt; i %26lt;%26lt; "=" %26lt;%26lt; sales[i] %26lt;%26lt; ", ";
cout %26lt;%26lt; "salary" %26lt;%26lt; i %26lt;%26lt; "=" %26lt;%26lt; salaries[i] %26lt;%26lt; endl;
}
delete[] sales;
delete[] salaries;
return 0;
}
elephant ear
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment