gpt4 book ai didi

c++ - 将数组传递给函数,不输出任何内容

转载 作者:行者123 更新时间:2023-11-28 05:24:16 24 4
gpt4 key购买 nike

我正在尝试创建一些东西,用 100 个介于 1 和 100 之间的随机数填充一个数组。当它在 main 函数中时它工作正常,但是当我把它放在一个 int 函数中时没有任何输出;我一定是错过了一些简单的东西,因为我才刚刚开始。我该怎么做才能解决这个问题?

 #include "stdafx.h"
#include <time.h>
#include <math.h>
#include <iostream>

int arrayer(int ar[101], int i);

int main()
{
srand(time(0));
int ar[101];

for (int i = 1; i < 101; ++i)
{
int arrayer(int ar[101], int i);
}
return 0;
}



int arrayer(int ar[101], int i) {


ar[i] = rand() % 100 + 1;

if (ar[i] < 10) {
std::cout << i << ": " << "0" << ar[i] << std::endl;
}

else {
std::cout << i << ": " << ar[i] << std::endl;
}

return ar[i];

}

最佳答案

您调用和声明的函数不正确。它应该是这样的:

#include "stdafx.h"
#include <time.h>
#include <math.h>
#include <iostream>

int arrayer(int ar[101], int i);

int main() {
srand(time(0));
int ar[101];

for (int i = 1; i < 101; ++i)
{
arrayer(ar, i);
}
return 0;
}

int arrayer(int* ar, int i) {
ar[i] = rand() % 100 + 1;

if (ar[i] < 10) {
std::cout << i << ": " << "0" << ar[i] << std::endl;
}

else {
std::cout << i << ": " << ar[i] << std::endl;
}

return ar[i];
}

另请注意,您没有使用返回值,因此如果永远不会使用它,您可以忽略它。

编辑:您实际上可以用这个替换 if-else 来打印值:

std::cout << i << ": " << setw(2) << setfill('0') << ar[i] << std::endl;

您需要包含 才能做到这一点。

关于c++ - 将数组传递给函数,不输出任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40868353/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com