This question already has answers here:
Program doesn't wait for user input with scanf("%c",&yn);
(5 answers)
scanf() leaves the newline character in the buffer
(7 answers)
Closed 13 days ago.
I am writing a simple converter to convert 3 metric measurements to British system values.I am supposed to write functions to solve it.
Below is the code I wrote.
#include <stdio.h>
void meter_to_feet(double,double);
void gram_to_pounds(double,double);
double Cel_to_Fahrenheit(double);
double target;
char letter;
int main(void){
printf("How many values to convert? ");
int time;
scanf("%d",&time);
//printf("%d\n",time);
for (int i=0;i<time;i++){
scanf("%lf",&target); //problem occurs here
scanf("%c",&letter); //and here
if('m'==letter){
meter_to_feet(target,3.2808);
}else if('g'==letter){
gram_to_pounds(target,0.002205);
}else if('c'==letter){
Cel_to_Fahrenheit(target);
}
}
return 0;
}
void meter_to_feet(double x,double y){
double r1;
r1=x*y;
printf("%0.6f ft\n",r1);
}
void gram_to_pounds(double x,double y){
double r1;
r1=x*y;
printf("%0.6f lbs\n",r1);
}
double Cel_to_Fahrenheit(double x){
double r1;
r1=x*1.8+32;
printf("%0.6f f\n",r1);
return r1;
}
I give it a .txt file looks like below to test this code in a step-by-step terminal and it passed.
4
12 m
14.2 g
3.2 c
19 g
However, when I complie and run above code using clang, I only get results of first two metric measurements--12m and 14.2g. It omitted the last two for some reason. I figured that I have to change my two scanf() lines into scanf("%lf %c",&target,&letter);in order to get desired output.
I wonder how exactly scanf() here, treats input in such scenario?
Related
Why is this code not running after printing of array if I take value of n>=9?
#include <stdio.h>
#include <math.h>
float mean_function(float array[],int n);
int main() {
int i,n;
float array[n],mean,sum=0,s2,summation,deno,C[i],elements;
printf("Enter No of Elements\n");
scanf("%d",&n);
printf("Enter Elements\n");
for(i=0;i<n;i++){
scanf("%f",&array[i]);
printf("%f",array[i]);
}
printf("sample variance(s2) : (sum((x-mean)*(x-mean)))/(n-1) /n");
printf("population variance(sigma2) : (sum((x-u)*(x-u))/n");
mean_function(array,n);
for(i=0;i<n;i++) {
deno=((array[i]-mean)*(array[i]-mean));
C[i]=deno;
summation=summation+C[i];
}
s2=((summation)/(n-1));
printf("s2=%f \n",s2);
}
float mean_function(float array[],int n) {
int i;
float sum=0,mean;
for(i=0;i<n;i++){ sum=sum+array[i]; }
mean=(sum/n);
return mean;
}
Why is this code not running after printing of array if I take value
of n>=9?
Some thoughts about your code (and about building programs in steps):
Arrays in C don't change in size once defined. VLAs are out for a variety of reasons. malloc() is in.
Use double, unless there is a specific reason to use floats.
Define and initialize one variable per line. Uninit vars can only result in an error as mentioned by #Jens.
Function declarations at the top (which you have done)
During development, there is no need to complicate things with a scanf (at least initially). It only adds an unwarranted layer of complexity. If you are testing statistical functions (mean, variance), put numbers in a pre-defined static array and verify functionality first.
C[i] as been declared with uninitialized i.
For this initial phase of building this program, I include a basic program.
I am not a fan of zero space between tokens (but ignore that)
Consider calling your array something other than 'array'.
Calculating the size of the samples array allows you to change the number of elements without changing anything else in code; which adds another layer of complexity to an already difficult phase.
#include <stdio.h>
#include <math.h>
double sample_mean(double* p, int n);
int main()
{
double samples[] = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 16.5, 2.3};
double mean = 0.0;
int size_samples = sizeof samples/sizeof(double);
printf("size_samples = %d\n", size_samples);
mean = sample_mean(samples, size_samples);
printf("Mean = %.2lf", mean);
}
// -------------------------------
double sample_mean(double* p, int n)
{
double mean = 0.0;
double total = 0.0;
for(int i = 0; i < n; i++)
total += *p++;
mean = total/n;
return mean;
}
Once this functionality is present (saved), you can start working on other stat functions. This way you can work step by step to get closer to the desired outcome.
Next up you can define sample_variance(double* p, int n) and work on that knowing that additional(new errors) are not coming from your code written so far.
Output:
size_samples = 8
Mean = 5.24
I hope it helps.
The code is likely not running because array[n] is declared with an uninitialized n. At the time you read n with scanf(), the array does not automatically "grow into the right size". You should either declare array big enough, or if you really want it to be user-defined, use malloc to allocate it (read the comp.lang.c FAQ) and all Stackoverflow questions tagged array...)
In addition, the scanf at some point fails. Note that when you enter numbers, you also have the "Enter" as a newline ('\n') in the input stream. You never read the newline so the next scanf fails.
This becomes obvious when you actually check the return value from scanf with code like this:
if (scanf("%f", &array[i]) == 1) {
/* successfully converted 1 item */
}
else {
/* scanf failed */
}
Usually what you want is to skip whitespace in the input. You do this by placing a space in the scanf format. Note that a single space tells scanf to skip any amount of white-space.
if (scanf(" %f", &array[i]) == 1) {
This question already has answers here:
Reading in double values with scanf in c
(7 answers)
scanf is collecting the wrong input
(3 answers)
Closed 4 years ago.
The code below compiles alright:
#include <stdio.h>
double add(double summand1, double summand2)
{
double sum;
sum = summand1+summand2;
return sum;
}
double subtract(double minuend, double subtrahend)
{
double diff;
diff = minuend-subtrahend;
return diff;
}
int main()
{
double a,b,c,d;
printf("Enter Operand 1:\n");
scanf("%d",&a);
printf("Enter Operand 2:\n");
scanf("%d",&b);
// Add
c = add(a,b);
// Subtract
d = subtract(a,b);
printf("Sum: %.3f\n", c);
printf("Difference: %.3f\n", d);
return 0;
}
However, when entering 5 and 5 the result is 0.000 (wrong) and 0.000 (expected).
When entering a decimal number (e.g. 2.5), the second prompt is skipped altogether and two random numbers are printed for sum and difference.
The problem must be with the data types double and float, which I seem to be using incorrectly.
In your scanf()you used the format specifier %dwhich is used for integers. As you declared your whole variables as doubles use %lf (floating point) instead. I tried the code and with the correct specifier, the Code works.
This question already has answers here:
How do I restrict a float value to only two places after the decimal point in C?
(17 answers)
Closed 6 years ago.
I've just started a class in C Programming, and while I have some background knowledge in JAVA, I'm trying to transition to this programming language. I have a project where I have to round user's input from something like 1.3333 to only two decimal places.
What I have so far is this:
#include <stdio.h>
int main (void)
{
//v is my variable for the value which the user will input
//Declaring variable as floating
float v;
printf("Enter your value: \n");
scanf("%.2f", &v);
v = 0;
printf("The rounded version is: %.2f");
return 0;
}
This is what I have so far based off of what I've read in my book and this link: Rounding Number to 2 Decimal Places in C which my question is different from because it involves user input. My professor does say that I can't use a library function and need to use simple type casts to calculate it. This makes me feel that what I have might be wrong. Would the #include <stdio.h> be considered a library function? Given this information, is my thought process on the right track? If not, then would I do something like divide by variable by 100? Maybe %e for scientific notation?
Thanks ahead of time! Only asking for specific information, not coding or anything. Really want to understand the "hows" and "whys".
First of all #include is a command that you need in order to include and use function that c provides for example for scanf you need to include library.
To round the number in two decimals without using %.2f in scanf you could write:
int x= (v*1000);
if(x%10>6) x=x/10+1 ;
else x= x/10;
printf("%d.%d",x/100,x%100);
I think your professor aims not so much in user input but rather in understanding what happens when converting basic datatypes. Rounding, or at least cutting off digits, without library functions could look as follows:
int main (void)
{
//v is my variable for the value which the user will input
//Declaring variable as floating
float v;
printf("Enter your value: \n");
scanf("%f", &v);
v = float((int)(v*100))/100;
printf("The rounded version is: %f", v);
return 0;
}
Input/Output:
Enter your value:
1.3333333
The rounded version is: 1.330000
Here is a working example that rounds properly without using any library calls other than stdio.
#include <stdio.h>
int main (void)
{
float v;
printf("Enter your value: \n");
scanf("%f", &v);
v = (float)((int)(v * 100 + .5) / 100.0);
printf("The rounded version is: %f\n",v);
return 0;
}
Output:
jnorton#mint18 ~ $ ./a.out
Enter your value:
3.456
The rounded version is: 3.460000
Take Float Input in a Row With Tabs
I want to take float input from the user a specific number of times in such a way that when the user presses the enter key, instead of going to the next line as scanf() automatically does, move the cursor one tab forward (\t).
Example:
5 -4 8 75
2 -7 4 11
Note: I'm using this code to get float values into an array for matrices.
I have tried a variation of the following:-
int i=0,interval=10;
float a[10]={0};
for (i=0;i<interval;i++)
{
scanf("%f",a[i]);
printf("\t");
i++;
}
OR
int i=0;
float a[10]={0};
while (a[i]=getche()!='\r')
{
printf("\t");
i++;
}
I would really appreciate it if someone helps me out.
If you were using windows, you can actually try:
#include <conio.h>
and:
char c[100];
int i = 0;
float f;
while ((c[i++]=getch())!='\t');
c[i++] = '\0';
f = atof(c);
Since getch() read characters instantly.
My teacher gave an assignment to me. The question is below:=
Write a program that prompts the user to enter 10 double numbers. The program should accomplish the follwing:
a. Store the information in a 10-element array.
b. Display the 10 numbers back to the user.
I could do all of the above in main().
Hint: You should use loops, not hardcode the values 0 through 9. It should be easy to convert your program to accept 1000 numbers instead of 10.
For a bonus mark, do at least one of the tasks (a or b) in a separate function. Pass the array to the function; do NOT use global (extern) variables.
I confused above. I wrote a program in the source code. Am I doing wrong? It is below:=
#include<stdio.h>
int main(void)
{
int number[10];
int i;
for (i = 0; i <10; i++)
printf("%d.\n", i, number[i]);
printf("\n\nPress [Enter] to exit program.\n");
fflush(stdin);
getchar();
return 0;
}
Thanks.
Not too bad so far, I'd like to make the following comments:
if you need to input double numbers, you should probably use double rather than int.
you need a statement (maybe in your current loop but possibly in another loop preceding the current one) which inputs the numbers. Look into scanf for this.
Using %d with printf is for integers, not doubles. You will have hopefully already figured out the format string to used when you looked into scanf above.
Bravo for using the correct int main(void) form and for not including conio.h :-)
Once you've figured those bits out, then you can worry about doing it in a separate function.
Based on the code you have given above, I would suggest reading up on the following:
scanf
functions in C, particularly passing arrays to functions: this link should be good.
Note to OP: If you were able to do (a) and (b) in main(), the code above is not complete. It would be nice the functions you created for getting (a) and (b) above done for getting to the root of your "confusion".
Let me know in case you need more help.
HTH,
Sriram
Try this it may sloves your problem.
#include<stdio.h>
int main(void)
{
double number[10];
int i;
printf("Enter double numbers:");
for (i = 0; i <10; i++)
scanf("%lf",&number[i] );
printf("The numbers you entered are:");
for (i = 0; i <10; i++)
printf("%lf\n",number[i] );
return 0;
}