[英]Reversing for loop
How can I reverse this for loop for the else statement?我怎样才能为 else 语句反转这个 for 循环? I am very open to criticism.
我对批评持开放态度。
int a = 1;
int ans;
ans=a;
int inp;
cout<<"type 1 for ascending and 2 for descending\n \n"<<endl;
cin>>inp;
if (inp==ans) {
const char* books[6]
= { "1 Literature", "2 Grammar", "3 Spelling", "4 Short Stories", "5 Alphabet", "6 Punctuations" };
for (int i = 0; i < 6; i++)
cout << books[i] << "\n";
return 0;
}
else{?}
I tried this and I believe I am very wrong LOL:我试过了,我相信我错了,哈哈:
else{
const char* books[6]
= { "1 Literature", "2 Grammar", "3 Spelling", "4 Short Stories", "5 Alphabet", "6 Punctuations" };
for (int i = 6; i > 0; i--)
cout << books[i] << "\n";
return 0;
}
#include<iostream>
#include<string>
int main()
{
int ans = 1;
int inp{};
std::cout << "type 1 for ascending and 2 for descending\n\n\n";
std::cin >> inp;
std::string books[6] = { "1 Literature", "2 Grammar", "3 Spelling", "4 Short Stories", "5 Alphabet", "6 Punctuations" };
if (inp == ans)
{
for (auto& book : books) // another way to do a range based for loop
{
std::cout << book << "\n";
}
}
else
{
for (int i{5}; i >= 0; i--) // your answer :)
{
std::cout << books[i] << '\n';
}
}
std::cin.ignore();
std::cin.clear();
std::cin >> ans; // so my terminal stays open
}
This is how you do it.这就是你如何做的。 Some tips: declare books outside the for loop no need to redeclare it everytime.
一些提示:在 for 循环之外声明书籍无需每次都重新声明。 Also the index of the last item in an array of size 6 is index 5 so we start there and go until we hit the 0th index and break.
此外,大小为 6 的数组中最后一项的索引是索引 5,因此我们从那里开始,然后是 go,直到我们到达第 0 个索引并中断。 also please look into syntax, you must have brackets on a for loop, even if it still compiles no one will like you if they are working with you and it will confuse you.
还请查看语法,你必须在 for 循环上有括号,即使它仍然可以编译,如果他们与你一起工作,没有人会喜欢你,这会让你感到困惑。 Hope you stick with it C++ is a beautiful language imho.
希望你坚持下去 C++ 是一种美丽的语言恕我直言。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.