I am working on a program in C that will take the input of a temperature from a user and return a substance and boiling point if it is within 3% of that substance's BP.
I have currently run into 2 issues that I can't seem to solve.
- The function
int find_substance(double value)seems to skip and not print some iterations. I have it set to print the index to make sure the indexes are chosen properly. I checked each value on the table and the only ones that don't print are -78.5, -35.5, and 3,280.00. - Another issue at hand is when I reach the 8th index, 2,212.00, it prints index = 9. Following this, each iteration prints index = 9, until I reach the last index where it prints nothing.
So what could cause an error like this?
I have checked the arrays to make sure there weren't any errors I missed and still have yet to find what is causing the problem.
#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;
}
}
valuevariable in themainfunction, useabs_tempin the call directly. Secondly, thereturnstatement returns immediately, no statements in the function will execute after it. Thirdly, theis_substance_within_x_percentfunction will never return-1. Fourthly, when the loop ends the value ofimight be equal to13which means it will be out of bounds.i == 13then you know nothing was found, so don't need to callis_substance_within_x_percentagain. Or you can justreturnfrom inside the loop instead of usingbreak, in which case if the loop ends then you don't have to check anything, you know nothing was found.is_substance_within_x_percent()is incorrect for negativetemparguments.abs(), which is an integer function. By using it, you will lose any fractional portion of the temperature. Usefabs()instead. Be sure to#include <math.h>, and link with-lm. That may explain your observed problem, since you're using it to check the value, and if the check fails, you skip printing anything on that loop iteration.