c-数组多次重复索引的可能原因是什么

  • 本文关键字:是什么 索引 数组 arrays c
  • 更新时间 :
  • 英文 :


我正在用C编写一个程序,该程序将从用户那里输入温度,如果温度在该物质BP的3%以内,则返回该物质和沸点。

我目前遇到了两个似乎无法解决的问题。

  1. 函数int find_substance(double value)似乎跳过并没有打印一些迭代。我将其设置为打印索引,以确保正确选择索引。我检查了表上的每个值,只有-78.5、-35.5和3280.00没有打印
  2. 手头的另一个问题是,当我达到第8个索引22212.00时,它会打印出索引=9。接下来,每次迭代都打印index=9,直到我到达最后一个索引,它什么都不打印

那么是什么原因导致了这样的错误呢?

我已经检查了阵列,以确保没有遗漏任何错误,但仍然没有找到问题的原因。

#include <stdio.h>
#include <stdlib.h>
const char* name[] = {"Carbon dioxide", "Ammonia", "Wax","Water", "Olive Oil", "Mercury", "Sulfur", "Talc", "Silver", "Copper", "Gold", "Iron", "Silicon"};
const double temp[] = {-78.5, -35.5, 45, 100.7, 300.00, 356.9, 444.6, 1,500.00, 2,212.00, 2,562.00, 2,700.00, 2,862.00, 3,280.00};
int is_substance_within_x_percent(double temp, double value);
int find_substance(double value);
int main()
{
double obs_temp;
printf("Enter the temperature: ");
scanf("%lf", &obs_temp);
double value = obs_temp;
int index = find_substance(value);


}
int is_substance_within_x_percent(double temp, double value)
{
temp = abs(temp);
if((value>=temp - (0.03 * temp)) && (value <=temp + (0.03 * temp))){
return 1;
}
else
return 0;
}
int find_substance(double value)
{
int index = 0;
int i;
for(i=0;i<13;i++)
{
if(is_substance_within_x_percent(temp[i], value) == 1){
printf("index: %d", i);
break;
}
}
return i;
if (is_substance_within_x_percent(temp[i], value)== -1){
printf("No substance was found.n");
return 0;
}
}

在字符串temp[]中,将千中数字的逗号改为正数,并删除任何多余的零,因为数组类型为double,因此不需要这些零(例如2562.00>>2562(。

同样在is_substance_within_x_percent中:添加value = fabs(value)并将temp = abs(temp)更改为temp = fabs(temp),因为这两个变量都是双变量,并且在计算之前需要每个变量的绝对值。

最新更新