该程序应根据人口和从其他城市到每个城市的步数,找到在该国家/地区建立距离为n的城市的邮局的最佳城市。 该程序有两个输入:第一行城市号和每个城市的第二行人口,以空格隔开。 输出的是从1开始的城市编号。
我通过IDK尝试了我的代码,为什么它返回一个随机数。
我是C的新手,很高兴见到您的帮助
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a=1;
while(a>0)
{
//var
int citynum,ways,result,min,maxpopulation,k;
//input number of cities
printf("Enter number of cities:\n");
scanf("%d", &citynum);
//check for number of cities (cities<1000000)
while(citynum>=1000000)
{
printf("cities should be less than a milion \nenter number of cities
again:\n");
scanf("%d", &citynum);
}
//make a list for population
int marks[citynum];
//entering populations
printf("enter population of each city with space\n");
for (int i = 0; i < citynum; i++)
{
scanf("%d", &marks[i]);
}
//check for the max limit of population (population<10^9)
for (int q = 0; q < citynum; q++)
{
maxpopulation= maxpopulation + marks[q];
}
while(maxpopulation>=1000000000)
{
maxpopulation=0;
printf("population should be less than 1000000000 \nenter populations
again;\n");
for (int i = 0; i < citynum; i++)
{
scanf("%d", &marks[i]);
}
for (int q = 0; q < citynum; q++)
{
maxpopulation= maxpopulation + marks[q];
}
}
//algoritm
int cityway[citynum];
for (k=0;k<citynum;k++)
{
//finding steps for each city and put it in a list
for(int l=0;l<citynum;l++)
{
ways=ways+marks[l]*l;
}
ways=ways-marks[k]*k;
cityway[k]=ways;
}
min=cityway[0];
for (int p=0;p<citynum;p++)
{
if(cityway[p]<min)
{
min=cityway[p];
result=p+1;
}
}
//show the result
printf("%d\n\n\n\n\n",result);
}
return 0;
}