[英]Calling function in C++
I'm trying to call a function with no return type but it doesn't seem to be getting called. 我正在尝试调用没有返回类型的函数,但似乎没有被调用。
The code looks something like this(summarized): 代码看起来像这样(总结):
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int ItemsInQuestion[4];
void GetQuestions(int NumQuests);
int main()
{
int NumberOfQuestions = 0;
srand((unsigned)time(NULL));
cout << "How many questions would you like?" << endl;
cin >> NumberOfQuestions;
cout << NumberOfQuestions << " questions will be asked.";
GetQuestions(NumberOfQuestions);
system ("PAUSE");
return 0;
}
void GetQuestions(int NumQuests)
{
for(int Questions=NumQuests; Questions>NumQuests; Questions++)
{
ItemsInQuestion[0]=(rand()%(263))+1;
ItemsInQuestion[1]=(rand()%(263))+1;
ItemsInQuestion[2]=(rand()%(263))+1;
ItemsInQuestion[3]=(rand()%(263))+1;
cout << ItemsInQuestion[0] << ' ' << ItemsInQuestion[1] << ' ' <<ItemsInQuestion[2] << ' ' << ItemsInQuestion[3];
}
}
The line that outputs the values in the array never comes up. 在数组中输出值的行永远不会出现。 What is causing this?
是什么造成的?
Because 因为
int Questions=NumQuests;
and 和
Questions>NumQuests;
don't like each other. 彼此不喜欢
You set Questions
to NumQuests
and then tell the loop to keep going as long as Questions
is strictly greater than NumQuests
, which it isn't to start off with. 你将
Questions
设置为NumQuests
,然后告诉循环继续,只要Questions
严格大于NumQuests
,它不是从开始。
Even if it was, you'd soon run into an overflow and undefined behavior . 即使它是,你很快就会遇到溢出和未定义的行为 。
This is not the way of using for-loops : 这不是使用for循环的方式:
for ( __Initialization, __Condition, __Increment)
As Grigore pointed out in his answer, your initialization is wrong. 正如Grigore在他的回答中指出的那样,你的初始化是错误的。 As
Questions=NumQuest
, the statement Questions>NumQuests
is false from the beginning, and your code is equivalent to 当
Questions=NumQuest
,语句Questions>NumQuests
从一开始就是假的,你的代码相当于
for ( ; 1<1 ; ) // I'm a lazy loop, I'm ugly and useless
There is an infinite number of way to do what you want : 有无数种方法可以做你想做的事:
// Direct : 0, 1, 2, .. NumQuest-1.
for (int Questions=0 ; Questions < NumQuests ; Questions++)
{ ... }
// Reverse : NumQuest, ..., 2, 1.
for (int Questions=NumQuests ; Questions > 0 ; Questions--)
{ ... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.