简体   繁体   English

打印数字 , C++

[英]Printing numbers , C++

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):你好,我写了代码,它看起来像这样(它从 a[] 中获取第一个数字,然后从 2 的幂中获取第二个数字,第三个是所有偶数):

#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我希望它打印出这些数字: Out: 124 142 214 248 284 518 520 588 610 626 644 680 716 786 914 948 984但我得到的是: 124 142 160 124 142 214 284 266 520 520 610 626 644 680 662 626 644 716 786 914 984 966 Out: 124 142 214 248 284 518 520 588 610 626 644 680 716 786 914 948 984 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.您错误地访问a[6] ,这是一种未定义的行为。

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).内置的下标表达式是这样工作的:如果我们对数组a执行a[b] ,那么它等价于*(a+b) ,而数组的第一个子对象存储在a (这里a指的是指针纯右值数组衰减到)。 Thus, to access the first element in an array, we use a[0] , ie *a因此,要访问数组中的第一个元素,我们使用a[0] ,即*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 .因此,如果你做一个简单的数学问题,最后一个有效的下标是size - 1 ,而不是size

I think here you need to change我觉得这里你需要改变

for (; a[i] < a[6]; i++)

to

for (; a[i] < a[5]; i++)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM