Hello I have written code and it looks like this (it tooks first number from a[], then second number from power of 2 and third all even numbers):
#include <iostream>
using namespace std;
int main()
{
int a[6] = { 1, 2, 5, 6, 7, 9 };
int i = 0;
int x;
int even = 0;
int sum;
for (; a[i] < a[6]; i++)
{
for (int power = 1; power <= 64; power *= 2)
{
x = power % 10;
for (int even = 0; even <= 6; even += 2)
{
sum = (a[i] + x + even);
if (sum % 7 == 0)
{
cout << a[i] << x << even << " ";
}
}
}
}
}
and I want it to print out those numbers : Out: 124 142 214 248 284 518 520 588 610 626 644 680 716 786 914 948 984
But instead I get those: 124 142 160 124 142 214 284 266 520 520 610 626 644 680 662 626 644 716 786 914 984 966
I don't know where's the problem,and numbers doubles couple of times. Please could somebody help me ?
You've wrongly accessed a[6]
, which is an Undefined Behavior.
the built-in subscript expressions work like this: If we perform a[b]
on an array a
, then it's equivalent to *(a+b)
, while the first subobject of the array is stored in a
(Here a
refers to the pointer prvalue the array decaying to). Thus, to access the first element in an array, we use a[0]
, ie *a
The number taking place in the declaration of an array is its size, formally speaking, the number of elements it can hold. Hence, if you do a simple math problem, the last valid subscript is size - 1
, not size
.
I think here you need to change
for (; a[i] < a[6]; i++)
to
for (; a[i] < a[5]; 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.