0
int substance[5]={0.15, 0.8, 35.3, 401, 46};

printf("Please select the substance: (1)Oak (2)Glass (3)Lead (4)Copper (5)Steel)");
scanf("lf%", substance[0])

In the array, I have the data for different material,

I want the user to type 1-5 and select one of the material. say, user select 2, the the following calculation will use number 0.8

3
  • So what have you tried and where is the problem? Also what is that scanf call supposed to do? Commented Feb 3, 2017 at 19:40
  • 1
    You have a confused mission: are you trying to select one of five materials, or are you trying to overwrite the property of Oak in the array? Moreover, the array as int[] is the wrong type: should be double[]. And scanf("lf%", substance[0]) should be scanf("lf%", &substance[0]) if that is the case. Commented Feb 3, 2017 at 19:42
  • 1
    int substance[5]={0.15, 0.8, 35.3, 401, 46}; WFT?? Is your intent to force integer rounding within the initialization? There isn't a technical problem, but it looks bad.... Commented Feb 3, 2017 at 19:52

1 Answer 1

3

There are some issues.

First, your substance-array should contain double-values, so its type should be double, too (not int). Second, if you ask the user for input, store the input in a separate variable (not in the substance-array). Try the following and use a debugger to see how a program behaves:

double substance[5]={0.15, 0.8, 35.3, 401, 46};

printf("Please select the substance: (1)Oak (2)Glass (3)Lead (4)Copper (5)Steel)");
int position=-1;
scanf("%d", &position);
double actualSubstance = -1;
if (position > 0 && position <= 5) {
  actualSubstance = substance[position-1];
}
// actualSubstance will contain the selected substance, or -1 if an invalid selection has been taken
Sign up to request clarification or add additional context in comments.

1 Comment

typo: "d%" should be "%d" (in scanf)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.