Question: Why won't my C++ code read negative input values? I'm inputting a file called data4twelve and it has negative numbers in it: 11 0.0 13.0

Why won't my C++ code read negative input values?

I'm inputting a file called "data4twelve" and it has negative numbers in it:

"11 0.0 13.0 27.0 -27.0 -9.0 5.0 11.0 1.0 21.0 -1.0 16.0"

Here's the output:

Input filename: data4twelve Input Array 2nd Array 11.00000 0.00000 0.00000 0.00000 13.00000 0.00000 27.00000 0.00000 0.00000 0.00000 0.00000 0.00000 0.00000 0.00000 0.00000 0.00000 0.00000 0.00000 0.00000 0.00000 0.00000 22.00000 0.00000 0.00000 0.00000 26.00000 0.00000 54.00000 0.00000 0.00000 0.00000 0.00000 0.00000 0.00000 0.00000 0.00000 0.00000 0.00000 0.00000 0.00000 Sum of all values in array 1: 51.00000 Sum of first 5 values in array 2: 0.00000

Here's my code:

#include #include #include #include #include using namespace std;

const int SIZE = 20;

void func1(double[], double[], int); double func2(double[], int);

int main() { double arr1[SIZE], arr2[SIZE]; double number; int count = 0, i = 0; string fname; ifstream myFile;

while(!myFile.is_open()) { cout << "Input filename: "; getline (cin, fname); myFile.open(fname.c_str()); } { while(myFile>>number) { arr1[i] = number; i++;

}

myFile.close();

func1(arr1, arr2, SIZE);

cout << "Sum of all values in array 1: " << func2(arr1,20) << endl; cout << "Sum of first 5 values in array 2: " << func2(arr2,5) << endl;

return 0; }

void func1(double arr1[], double arr2[], int size) { for (int i = 0; i < 10; i++)

{ arr2[i + 10] = 2 * arr1[i]; arr2[i] = cbrt(arr1[i + 10]); } cout << right << setw(15) << fixed <<"Input Array" << "\t" << right << setw(1\ 4) << fixed << "2nd Array" << endl; for (int i = 0; i < size; i++) { cout << setprecision(5) << fixed; cout << right << setw(15) << arr1[i]; cout << setprecision(5) << fixed; cout << right << setw(15) << arr2[i] << endl; } return; }

double func2(double arr[], int n) { double sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; return sum; }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!