不能将相同的 i 用于不同的任务,为什么?
can't use same i for different tasks,why?
将相同的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
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 为什么在全局范围内使用"extern int a"似乎不行?
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 为什么会发生堆损坏
- 为什么使用 "this" 指针调用派生成员函数?
- 为什么我的 FreeRTOS 任务看不到类成员?
- 为什么我在启动任务时收到成功代码,但它什么也不做?
- 为什么可以进行此任务?
- 为什么在任务后打电话给攻击函数
- 为什么我的并行任务管理如此缓慢
- 在将函数分配给函数指针时,为什么可以多次使用取消任务运算符
- 为什么与C相比,linker在C++中的任务更艰巨
- 试图解决卡蒂斯任务"Coast" - 无法弄清楚为什么我有点不对劲
- 为什么此代码在通过任务计划程序运行时不起作用
- 不能将相同的 i 用于不同的任务,为什么?
- 为什么 for/while/do-while 在执行相同的任务时被放置在 c/c++ 中
- 为什么这个简单的任务没有定义行为
- 为什么任务集对Fedora没有影响