不能将相同的 i 用于不同的任务,为什么?

can't use same i for different tasks,why?

本文关键字:任务 为什么 不能 用于      更新时间:2023-10-16

将相同的i用于不同的目的似乎效果不佳,为什么会这样?

#include<iostream>
using namespace std;
int main()
{
    int g,n,i=0,sum;
    cin>>g;
    while(i<g)
    {
        cin>>n;
        int a[n];
        for(i=0;i<n;i++)
            cin>>a[i];
        for(i=0;i<n;i+=2)
        {    
           "code"
        }
        cout<<sum;
        i++;
    }
    return 0;
}

如果m在while和loop中使用相同的i,代码就不起作用,但是如果我在两者中使用不同的参数,代码就起作用了。参数的任务是存储计数器。那么它为什么不起作用呢?

使用以下代码作为程序的模板。至于代码中的错误,你可以在帖子的评论中找到它们的描述。:)至少这个循环

    for(i=0;i<n;i++)
    {    
        sum=a[0];
        sum+=a[i];
    }

没有任何意义。

给你。

#include <iostream>
void bubblesort( int a[], size_t n )
{
    for ( size_t i = 0; i < n; i++ )
    {
        for ( size_t j = 0; j < n - i - 1; j++ )
        {
            if ( a[j + 1] < a[j] )
            {
                int x = a[j];
                a[j] = a[j + 1];
                a[j + 1] = x;
            }
        }
    }
}

int main() 
{
    std::cout << "Enter number of elements: ";
    size_t n = 0;
    std::cin >> n;
    if ( n != 0 )
    {
        int *a = new int[n];
        std::cout << "Enter " << n << " integers: ";
        for ( size_t i = 0; i < n; i++ ) std::cin >> a[i];
        std::cout << "Original numbers:";
        for ( size_t i = 0; i < n; i++ ) std::cout << ' ' << a[i];
        std::cout << std::endl;
        bubblesort( a, n );
        std::cout << "Sorted numbers:";
        for ( size_t i = 0; i < n; i++ ) std::cout << ' ' << a[i];
        std::cout << std::endl;
        long long sum = 0;
        for ( size_t i = 0; i < n; i++ ) sum += a[i];
        std::cout << "Sum of the numbers is " << sum << std::endl;
        delete [] a;
    }
    return 0;
}

例如,如果要进入

10
9 8 7 6 5 4 3 2 1 0

那么输出将是

Original numbers: 9 8 7 6 5 4 3 2 1 0
Sorted numbers: 0 1 2 3 4 5 6 7 8 9
Sum of the numbers is 45