我的代码生成一个随机整数输出,我不知道为什么
我在作业程序的输出方面遇到困难,并且无法弄清楚是什么导致了我的问题。代码如下:
#include <stdio.h>
int find_minimum(int *a, int n)
{
int *last=(a + n);
int minimum = *a;
while(a!=last){
if(*a < minimum)
minimum=*a;
a++;
}
return minimum;
}
int main()
{
int N;
printf("Enter number of parts (N): ");
scanf("%d",&N);
int K;
printf("Enter number of part types (K): ");
scanf("%d",&K);
int a[K];
printf("Enter Part list:\n");
for(int i=0;i<N;i++){
int part;
scanf("%d",&part);
a[part-1]+=1;
}
printf("The factory can build %d computer(s)",find_minimum(a,K));
return 0;
}
该程序应该输入零件的数量和零件的类型,然后计算输入的零件可以组成多少种可能的计算机组合。我得到的示例输入如下所示:
Enter the number of parts (N): 10
Enter the number of types of parts (K): 2
Enter part list:
1 1 1 1 1 2 2 2 2 2
The factory can build 5 computer(s)
将这些数字输入程序后,我得到一个随机生成的整数,这不是预期的结果。任何帮助将不胜感激!
I am having difficulties with the output of a program for an assignment and I cannot figure out what is causing my problem. The code is as follows:
#include <stdio.h>
int find_minimum(int *a, int n)
{
int *last=(a + n);
int minimum = *a;
while(a!=last){
if(*a < minimum)
minimum=*a;
a++;
}
return minimum;
}
int main()
{
int N;
printf("Enter number of parts (N): ");
scanf("%d",&N);
int K;
printf("Enter number of part types (K): ");
scanf("%d",&K);
int a[K];
printf("Enter Part list:\n");
for(int i=0;i<N;i++){
int part;
scanf("%d",&part);
a[part-1]+=1;
}
printf("The factory can build %d computer(s)",find_minimum(a,K));
return 0;
}
This program is supposed to take input for the amount of parts and how many types of parts there are, and then calculate how many possible combinations of computers can be made out of the parts entered. The example input I was given looks like:
Enter the number of parts (N): 10
Enter the number of types of parts (K): 2
Enter part list:
1 1 1 1 1 2 2 2 2 2
The factory can build 5 computer(s)
Upon entering these numbers into the program, I get a randomly generated integer, which is not the intended result. Any help would be appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您声明了数组,但没有初始化它。这意味着数组的每个槽内部都没有 0,但可以有一个随机值。
因此,执行 a[part-1] += 1 会将 1 添加到随机值(请注意,如果 part 为 0 或 > 到 k,则超出范围)。你需要将每个“槽”初始化为 0。
尝试编译并执行它来理解:
You declared your array but you did not initialize it. It means that every slot of your array does not have a 0 inside but can have a random value in it.
So doing a[part-1] += 1 add 1 to a random value (note that if part is 0 or > to k you are out of bound). You need to initialize every "slot" to 0.
try to compile and execute this to understand: