I just started to learn C programming.
In my book there is this piece of code:
/*Code Start*/
/*This code is use to find the simple interest*/
main ()
{
int p, n;
float r, si;
p = 1000;
n = 3;
r = 8.5;
si= p*n*r/100;
printf("%f", si);
}
/*Code end*/
The output i got was " 255.000000 "
I though i'll modify it with scanf function so i wrote this:
/*Code Start*/
main ()
{
int p, n;
float r, si;
printf("Enter value for p: \n");
scanf("%d", &p);
printf("Enter value for n: \n\n");
scanf("%d", &n);
printf("Enter valuse for r: \n\n");
scanf("%d", &r);
si= p*n*r/100;
printf("\nYour Simple Interest is %f\n\n", si);
}
/*Code End*/
No matter what values i give to p,n,r the answer i get is always 0.000000..
I also tried giving the values, p=1000, n=3, r=8.5 but still i get 0.000000..
Change the specifier in scanf. You're using %d instead of %f:
scanf("%f", &r);
^
First side note: the code looks kind of bad (no return type for main ?!). Are you sure it's a good book ?
Second side note: using floats today is kind of pointless. Maybe you
should use doubles ?
Firstly, your main problem: The %d specifier is only for integers, not floats or doubles. Use %f for floats.
In addition, the main should return an int, this will do:
int main() {
/* your code */
return 0;
}
Finally, I would recommend you make better use of white-space as it will vastly help with readability once you start making larger programs.
Use %f conversion specification to read a float:
scanf("%f", &r);
%d means it reads a decimal integer and not a float.
r is a float, but you're reading it in using %d as a scanf specifier, which expects an int.
The real culprit in your code is the line scanf("**%d**", &r).
%d is the format specifier for integer value, as you declared r as float then use %f instead of %d.
i.e. scanf("%f", &r)
Change Either
int p, n;
float r, si;
to
int p, n,r;
float si;
or change formate specifier in scanf("%d", &r); %d to %f.
when you declare r as an integer r=8 will be considered, in that case scanf("%d", &r); will be accepted. and your program get compiled and executed.
both declaration and formate specifier should be same.
my suggestion is to use %.2f when dealing with money. which will give like 10.00 which is the correct formate.
Related
I am trying to write a sort of calculator program and i can get everything but my factorial and power functions to work. They output a number in the millions no matter how small the number is and i don't see a problem with the code. (I just started learning C recently so assume the extent of my knowledge is everything in this code)
int iFactorial(num1){//needs help returns a number in the millions no matter what
int i, factorial=1;
printf("Enter a positive number: ");
scanf("%d", &num1);
for(i=1; i<=num1; i++)
factorial*=i;
printf("The factorial is %i", &factorial);
return 0;
}
int fPower(num1,num2){//needs help, same as above
int i, number = 1;
printf("Enter the number you want to raise to a power: \n");
scanf("%d", &num1);
printf("Enter the exponent: ");
scanf("%d", &num2);
for(i=0; i<num2; i++)
number*=num1;
printf("%d to the %d equals %d", &num1, &num2, &number);
return 0;
}
You are using & in the print statement that prints the address of the variable used.
Correct the statements in their respective function as follows :
printf("The factorial is %i", factorial);
printf("%d to the %d equals %d", num1, num2, number);
Your printf for the factorial and power cases are mal-formed, you are passing the arguments by pointer; you need to pass them by value.
After that, you'll realise quickly that you'll overflow the int type in the factorial and power cases. An int in general is only good up to and including 7! in truly portable C++. Consider using an unsigned long long, which will give you values up to and including 21!. Use "%ull" for an unsigned long long in the formatter.
Finally, pass the types explicitly to your functions in C: your style has been explicitly disallowed since C99.
You're using the wrong format specifiers to printf to print the results, and you're not passing the actual values you want to print:
printf("The factorial is %i", &factorial);
You're passing in the address of factorial instead of its value, so it's printing that instead. Just pass the result directly instead of its address:
printf("The factorial is %i", factorial);
I was trying c code to add but my program doesn't execute, codeblocks unfortunately closes. What is the error?
void main()
{
float a,b;
printf("%30sAddition Of Numbers\n");
printf("\nEnter Number 1: ");
scanf("%f",&a);
printf("\nEnter Number 2: ");
scanf("%f",&b);
printf("\nThe addition of %0.3f and %0.3f is %0.3f",a,b,(a+b));
}
I want to put the result of addition directly in printf statement with float inputs but I am not getting it working.
I also tried putting the result in variable a but it didn't work either.
void main()
{
float a,b;
printf("%30sAddition Of Numbers\n");
printf("\nEnter Number 1: ");
scanf("%f",&a);
printf("\nEnter Number 2: ");
scanf("%f",&b);
a=a+b;
printf("\nThe addition of %0.3f and %0.3f is %0.3f",a,b,a);
}
where am I going wrong?
The problem is in the following statement
printf("%30sAddition Of Numbers\n");
here, the format string supplied to the printf() conatins %30s (or, %s, in general) which is a format specifier (conversion specifier), and you did not supply any argument to it. It invokes undefined behavior.
To quote C11 standard, chapter ยง7.21.6.1
[...] If there are insufficient arguments for the format, the behavior is
undefined. [...]
You can also check the man page to find out more about the format specifiers.
EDIT:
As discussed in the below comments, if you want some spaces to appear before the output, change
printf("\t\tAddition Of Numbers\n");
That said,
void main() should be int main (void), at least, to conform to the standards.
You should always check the return value of scanf() to ensure the successful scanning.
The "%30sAddition Of Numbers\n" issue in your post has been addressed by two good answers (at the time of this post). But you asked a question in comments that may not have been answered completely:
works with %30s when i use all integer numbers and not float! how do i make it work with floats.
A generic answer to that question:
The format specifier you use in scanf(): "%f",&a could result in undesirable results if scanning in unexpected newlines, spaces or other white space. This can be addressed by modifying the format specifier string to suppress these characters. Here is a suggestion:
char* fmt = "%[^\n]%*c";//This generic format specifier, can be used for both integer
//and floating point inputs when used in conjuction
//with strtod() or strtol() (see below)
scanf(fmt, input);
Explanation of "%[^\n]%*c".
When a user is asked to enter a generic number, it might be a float or an integer. You can accommodate that by creating methods for both, and being specific about what kind of value you would like to process:
float get_float(void)
{
char input[80];
char **dummy={0};
char* fmt = "%[^\n]%*c";
printf("Enter floating point number and hit return:\n");
scanf(fmt, input);
return strtod(input, dummy);
}
long get_int(void)
{
char input[80];
char **dummy={0};
char* fmt = "%[^\n]%*c";
printf("Enter integer number and hit return:\n");
scanf(fmt, input);
return strtol(input, dummy, 10);
}
Called like this:
int main(void)
{
long integer_var = get_int();
float float_var = get_float();
float sum = (float)integer_var + float_var;
return 0;
}
Try adding getch(); function at the bottom before closing curly brackets,
like this
void main()
{
float a,b;
printf("%30sAddition Of Numbers\n");
printf("\nEnter Number 1: ");
scanf("%f",&a);
printf("\nEnter Number 2: ");
scanf("%f",&b);
a=a+b;
printf("\nThe addition of %0.3f and %0.3f is %0.3f",a,b,a);
getch();//it will hold your output screen so you can see the output
}
In this line
printf("%30sAddition Of Numbers\n");
you did not supply a string argument for the %s format. This causes undefined behaviour.
If you want the output spaced, you could try a small modification
printf("%30s\n", "Addition Of Numbers");
in this case you are supplying a string literal to satisfy the %s format.
Additionally you must always check the return value from scanf to see that it did convert the number of arguments it was supposed to. It's a basic newbie error not to, and the root cause of hundreds of SO questions.
I am trying to read in a double value continuously from the user using scanf.
Code:
printf("Enter A value: \n");
double input;
int result = scanf("%f", &input);
printf("INPUT: %f\n", input);
The output is
INPUT: 0.000
You lied to the compiler: when scanning, %f says you supply a pointer to float. But you provided a pointer to double.
To fix, either use %lf or declare input as float.
Note that there is an asymmetry with printf formats, which uses %f for both float and double arguments. This works because printf arguments are promoted to double (and are not pointers).
I am trying to read in a double value continuously from the user using scanf.
To do so you need a loop, like the following:
while(scanf("%lf", &input) == 1) {
//code goes here...
printf("INPUT: %lf\n", input);
//code goes here...
}
Note that, as the primitive type of input is double, you need to use %lf instead of %f (%fused for float).
For years, I don't do anything in C and now I can't do simple things, I was accustomed to cin and cout and now Java. I was trying to make a simple program to calculate the average X amount of exams notes. The output are "random numbers" and checking to interrupt the program occurs before entering a note. Why is that?
#include <stdio.h>
int main(void) {
int numeroDeNotas;
float nota = 0.0;
float notaAuxiliar = 0.0;
char continuar;
int media;
do{
printf("Enter the exam grade\n");
scanf("%f", ¬aAuxiliar);
nota += (int) notaAuxiliar;
numeroDeNotas++;
printf("Do you want to continue? Enter n if you want to stop\n");
scanf("%c", &continuar);
}while(continuar != 'n');
printf("%d\n\n", nota);
printf("%d\n\n", numeroDeNotas);
media = nota/numeroDeNotas;
printf("Average grade: %d", media);
return 0;
}
nota is a float, but you are using %d format code to print it. %d expects an int; you need %f to print floating point numbers.
C's standard I/O formatting is definitely not typesafe. When you provide a format code, you have to make sure the corresponding argument has the right type. However, if you had compiled with the -Wall option (at least, with gcc or clang), the compiler would have warned you.
Also, scanf("%c", &continuar); reads a single character without skipping whitespace, which will be the character immediately following the number read by scanf("%f", ¬aAuxiliar);. That character is most likely a newline. You need to skip whitespace before reading the y or n, so you could use:
scanf(" %c", &continuar);
numeroDeNotas was declared with a variable type - float. So you can't use %d later in your code when writing a printf statement.
numeroDeNotas
variable is declared but no where initialized. and you are incrementing in do while loop.
media = nota/numeroDeNotas;
printf("Average grade: %d", media);
and you are using garbage value to calculate media which is undefined output. initialize numeroDeNotas to zero.
I am trying to learn C and have come up with the following small program.
#include "stdafx.h"
void main()
{
double height = 0;
double weight = 0;
double bmi = 0;
printf("Please enter your height in metres\n");
scanf_s("%f", &height);
printf("\nPlease enter your weight in kilograms\n");
scanf_s("%f", &weight);
bmi = weight/(height * height);
printf("\nYour Body Mass Index stands at %f\n", bmi);
printf("\n\n");
printf("Thank you for using this small program. Press any key to exit");
getchar();
getchar();
}
The program compiles perfectly, however the answer returned by the program does not make sense. If I enter 1.8 for height and 80 for weight, the bmi is like 1.#NF00 which does not make sense.
What am I doing wrong?
When using scanf with a double, you must use the %lf specifier, as pointers are not promoted with scanf.
For more info, read the following question:
Why does scanf() need "%lf" for doubles, when printf() is okay with just "%f"?
scanf (and scanf_s) format %f expects pointer to type float.
Simply change the type of your height and weight variables to float to fix this.
I think issue in scanf_s syntaxis, you ommited 3-rd argument, which is size of buffer in bytes. Try following:
scanf_s("%lf", &valueToGet, sizeof(double));
the drawback of the scanf() and printf() is that it requires very strict format, any mismatch between the control string and the argument can cause drastic error which makes your input or output make no sense at all. And that mistake is often made by beginners.
If you're using %f format specifier, then you must use float data type instead of double.
The problem is because:
format '%f' expects argument of type 'float*', but argument 2 has type 'double*'
There are two ways to handle this:
Either the variables should be float:
double height = 0; --> float height = 0;
double weight = 0; --> float weight = 0;
double bmi = 0; --> float bmi = 0;
or the format specifier should correspond to double.
scanf_s("%f", &height); --> scanf_s("%lf", &height);
scanf_s("%f", &weight); --> scanf_s("%lf", &weight);
printf("\nYour Body Mass Index stands at %f\n", bmi);
|
V
printf("\nYour Body Mass Index stands at %lf\n", bmi);