C++ FOR LOOP ONLY task
C++ FOR LOOP ONLY task
好的,所以我有这个C++任务,通过使用ONLY for循环,我必须创建这个表
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
到目前为止,有了这行代码:
int n;
int count = 1;
cout << "Please enter N: "; cin >> n;
for (int i = 1;i<=n;i++)
{
cout << i << ", ";
for (int j = count;j<n;j++)
{
count+=n;
cout << count << ", ";
}
cout << endl;
}
我设法只得到
1 5 9 13
2
3
4
我下一步该怎么办?
你走在了正确的轨道上。您应该注意,行中任意两个连续条目之间的差为n,第一个条目是行号。
for (int i = 1;i<=n;i++)
{
// loops from 0 to n-1
for (int j = 0;j<n;j++)
{
cout << i + j*n << " ";
}
cout << endl;
}
如果您想反转偶数行,那么对于这些行,您将向后运行for循环。
for (int i = 1;i<=n;i++)
{
if ( i % 2 == 1 ) {
for (int j = 0;j<n;j++)
cout << i + j*n << " ";
} else {
for (int j = n-1; j>=0 ; j-- )
cout << i + j*n << " ";
}
cout << endl;
}
如果您想反转偶数列,那么您可以看到模式。
for (int i = 1;i<=n;i++)
{
for (int j = 1; j <= 4 ; j-- )
{
if ( j % 2 == 0 ) {
cout << (5-i) + (j-1)*n << " ";
}
else
cout << i + (j-1)*n << " ";
}
cout << endl;
}
问题是count
需要在内部for
循环之后或之前重置:
for (int i = 1;i<=n;i++)
{
cout << i << ", ";
// ***
count = i;
// ***
for (int j = count;j<n;j++)
{
count+=n;
cout << count << ", ";
}
cout << endl;
}
你可以把它简化为Abishek的答案。
This problem can be solved by doing this coding.
#include<iostream>
#include <conio.h>
using namespace std;
main()
{
int i,j,n;
for (i=1;i<=4;i++)
{
n=i;
for (j=1;j<=4;j++)
{
cout<<n<<"t";
n=n+4;
}
cout<<endl;
}
getch ();
return 0;
}
#include <iostream>
using namespace std;
int main()
{
for (int i = 1 ; i <= 13 ; i +=4)
{
cout << i << " " ;
}
cout << endl;
for (int x = 2 ; x <= 14 ; x+=4)
{
cout << x << " " ;
}
cout << endl;
for (int y = 3 ; y <= 15 ; y+=4)
{
cout << y << " ";
}
cout << endl;
for (int z = 4 ; z <= 16 ; z+=4)
{
cout << z << " " ;
}
cout << endl;
}
这是我的答案。我在Microsoft Visual C++2010学习版上写了它,它给了我书面答案。
相关文章:
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 使用"Task"函数指针队列定义作业管理器
- 这对"With a stackless coroutine, only the top-level routine may be suspended."意味着什么
- Visual Studio C++ Project File CustomBuild Task: Filter Outp
- 如何修复输出日志中的"EnableInput can only be specified on a Pawn for its Controller"错误
- 如何理解"abstract-declarator containing an ellipsis shall only be used in a parameter-declaration"
- 开发QR扫描仪以扫描我生成的"only" QR码?
- Protobuf 生成的C++类无法针对 iOS 进行编译,并显示错误"Only virtual member functions can be marked 'final'"
- Windows 10 环境中的"This version of XAudio2 is available only in Windows 8"错误
- CUDA 内核"Only a single pack parameter is allowed"解决方法?
- 为什么仅 -fno-signed-0 就可以实现优化,而似乎也需要 -ffinite-math-only (gcc)
- 在 c++11 模式下使用 QtConcurrent::run with move only 参数
- 为什么这句话"The expression can be used only as the left-hand operand of a member function call"在 [expr.re
- 如何将C std ::未来返回值调整到C#System.Threading.tasks.task
- 平息海湾合作委员会的"only available with -std=c++XX or -std=gnu++XX"警告
- 为什么 std::optional 不允许"move construct and copy assign only"类型的移动分配?
- "useinbandfec is a unidirectional receive-only parameter"作品中是什么意思?
- 犰狳/ Xcode:无处"functions that differ only in their return type cannot be overloaded"错误
- SDL_LoadBMP only returning NULL
- C++ FOR LOOP ONLY task