This is my first time using C++ and I am writing a small program to sum up to ten numbers (doubles) that will be entered in the command prompt.
I have written the following code and I cannot figure out why it will not produce the desired result.
int main()
{
double num[10];
double sum = 0;
int i;
int n = 10;
while (scanf_s("%lf", &num) != EOF)
{
for (i = 0; i < n; ++i)
{
scanf_s("%lf", &num);
sum = sum + num[i];
}
}
cout << sum;
system("pause");
return 0;
}
The data entry is terminated with a control D. In my eyes it should run fine but it doesn't. Could someone please give me some pointers for solving this, I don't just want to be told the correct way I would rather learn it myself.
The problem is that &num is the address of the array. SO you read your value always in num[0]
meaning that num[i]
is random in most of the cases.
Try to change your loop:
for (i = 0; i < n && (cin>>num[i]); ++i)
{
sum = sum + num[i];
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.