I am in a intro to C programming course and I am a bit confused.
My input is not working correctly. When I run the program, the program will take the first input, then skip the rest of the prompts for inputs and generate a total.
What is going on? I am completely lost.
int main(void) {
/* declarations: */
double y, m1, s1, s2, m2, i;
char g; /* Do not remove this line */
/*Print the title of the program*/
printf(" MILEAGE SPEED INTERPOLATION\n");
printf("______________________________________________________________________\n");
printf("Enter in your first speed:\n"); //this is s1
scanf("%.1f", &s1);
printf("Enter in your mileage:\n"); //m will be mileage 1
scanf("%.1f", &m1); //mileage is y
printf("Enter in your second speed:\n"); //this is s2
scanf("%.1f", &s2);
printf("Enter in your second mileage:\n");
scanf("%.1f", &m2);
/*Get the needed input*/
/*get the interpolation from the user*/
printf("Enter your interpolation:\n"); //number between 1 and 2
scanf("%.lf", &i);
printf("______________________________________________________________________\n");
/*Statements that perform the desired task*/
// This equation is calculating from rpm to knots
y = m1 + (i - s1) * (m2 - m1) / (s2 - s1); //This will do the equation for us.
/* Printing of the results*/
// Trying to print the answer from above equation
printf("Your estimated value is %f: ", y);
/*Keeps the window open. Please do not alter this.*/
printf("\n\nEnter to q to quit.\n");
do {
g = getchar();
} while (g != 'q');
return 0;
}
You must use "%lf" for double with scanf()
if (scanf("%lf", &s1) != 1)
return -1; /* Bad input */
and you can't specify precision, instead you can specify a maximum number of characters.
Related
For my homework, I am trying to code a calculator which can also calculate average of taken numbers. I don't want to ask for number of numbers because our teacher don't want it in that way. So I thought of scanning values until the user presses "p". But as you would guess, the numbers are float and "p" is a character. What I want to do is assigning the value scanned to both of them if it is possible. I tried different ways, played with the codes but it isn't working properly. So I am seeking your advice.
It prints a value when p is inputted as like 3rd, 5th, 7th (oddth) number (sometimes right, sometimes wrong but I can fix it if I figure this out). But it doesn't print a value in other occasions and expects infinite inputs from the user.
This is the code I have written for this. scanf("%f %c", &number1, &pause); command is where I want to know about, actually.
#include<stdio.h>
float number1, number2, i, result;
char pause;
int main() {
scanf("%f", &number1);
i = 0;
while (pause != 'p') {
number2 = number1 + number2;
scanf("%f %c", &number1, &pause);
i++;
}
result = number2 / (i - 1);
printf("%f", result);
}
Use double not floats if there is no specific reason to do so (like using uC without double FPU).
You do not initialize the variables
Always check the result of the I/O operation.
#include <stdio.h>
int main ()
{
double number1= 0, number2 = 0, i = 0, result = 0;
char pause = 0;
char line[128];
while (pause != 'p')
{
if(fgets(line, sizeof(line), stdin))
{
if(sscanf(line, "%lf %c",&number1, &pause) != 2)
{
printf("Wrong input - try again\n");
pause = 0;
continue;
}
number2 = number1 + number2;
i++;
}
else
{
// do something with I/O error
}
}
result = number2 / (i-1);
printf("%lf",result);
}
You can play with it yourself : https://onlinegdb.com/Hy3y94-3r
I noticed 3 problems with your code.
First I would advise you to use meaningful variables names. number1, number2, etc. and the i which represents the number of inputs given can be an int instead of a float.
Secondly, you lack of printing to the user what's going on in your program; it's better to have messages like "enter your number, do you wanna stop? the result is...etc".
Lastly, having two inputs in one line of code can make it hard to debug, knowing that reading strings and characters in C is already hard for beginners. For example, %c does not skip whitespace before converting a character and can get newline character from the previous data entry.
Here is my fix: I changed some variables' names, printed some messages and read the two inputs in two different lines with adding scanf(" %c") with the space to avoid that problem.
#include<stdio.h>
float sum, temp, result;
int nb;
char pause;
int main () {
pause='a';
while (pause != 'p'){
printf("Enter your number: ");
scanf("%f",&temp);
sum+=temp;
nb++;
printf("type 'p' if you want to stop: ");
scanf(" %c",&pause);
}
result = sum / nb;
printf("the average is : %f",result);
}
I tested it, should work fine
Edit: after explaining that you don't want to ask the user each time, here is how the code should work (the case that the user don't input a float is not treated, and just take it as zero
#include<stdio.h>
#include<string.h>
#include <stdlib.h>
float sum, temp, result;
int nb;
char input[50];
int main () {
sum=0;
nb=0;
printf("Enter your numbers, then type 'p' to stop\n");
do{
printf("Enter your next number: ");
scanf("%s", input);
if(strcmp(input,"p")!=0)
{
float temp= atof(input);
sum+=temp;
nb++;
}
}while(strcmp(input,"p")!=0);
if(nb!=0)
result = sum / nb;
printf("\nThe average is : %f",result);
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
whats wrong in my code? it doesn't give the values properly and when i insert q it doesn't execute properly....
#include<stdio.h>
void main()
{
double a=0, x, ctot;
double y, stot;
char b, c='q';
double score=x*y;
while(a<200){
printf("Enter no of Credits of the subject = ");
scanf("%lf\n",&x);
printf("Enter the score for the subject = ");
scanf("%lf\n",&y);
scanf("%c\n",&b);
if(b=='q'){
break;
}else{
ctot+=x;
stot+=score;
a++;
}
}
printf("GPA of the student = %f\n", stot/ctot);
}
An attempt to access a variable with indeterminate value (meaning uninitialized) invokes Undefined Behavior and the valid operation of your code ceases at that point. It can appear to work properly or SegFault or anything in between.
To avoid uninitialized values, always initialize them -- especially when you are just beginning to program. (it will save you from yourself...), e.g.
int a = 0; /* always initialize all variables - good practice */
double ctot = 0.0,
stot = 0.0,
score = 0.0,
x = 0.0,
y = 0.0;
char c = 0;
The proper declarations for main are int main (void) and int main (int argc, char **argv) (which you will see written with the equivalent char *argv[]). note: main is a function of type int and it returns a value. See: C11 Standard ยง5.1.2.2.1 Program startup p1 (draft n1570). See also: See What should main() return in C and C++?
While there are some ancient compilers, and some micro-controllers that allow void main(), it is a non-standard invocation, and any worthwhile compiler will warn. (you are compiling with compiler-warning enabled right?, e.g. -Wall -Wextra for gcc/clang or /W3 for VS (cl.exe))
You must check the return of scanf every time and validate the return is equal to the number of conversions you have requested -- otherwise a matching or input failure has occurred (or the user canceled by generating a manual EOF). This is the only way you can insure you are processing valid data and not further invoking Undefined Behavior (or throwing yourself into an endless input loop). You must always empty stdin after each input. Your '\n' gimick in the format string will not work. A simple way to empty stdin is to define a helper-function to call after each input to remove any extraneous or additional characters that remain unread, e.g.
/* simple function to empty remaining chars in stdin */
void empty_stdin (void) /* if no parameter - spcecify 'void' explicitly */
{
int c = getchar();
while (c != '\n' && c != EOF)
c = getchar();
}
...
printf ("Enter no of Credits of the subject = ");
if (scanf ("%lf", &x) != 1) { /* validate EVERY input */
fprintf (stderr, "error: invalid input for 'x'.\n");
return 1;
}
empty_stdin(); /* empty stdin, your \n gimick doesn't work */
Putting it altogether, you could do something similar to the following:
#include <stdio.h>
/* simple function to empty remaining chars in stdin */
void empty_stdin (void) /* if no parameter - spcecify 'void' explicitly */
{
int c = getchar();
while (c != '\n' && c != EOF)
c = getchar();
}
int main (void) {
int a = 0; /* always initialize all variables - good practice */
double ctot = 0.0,
stot = 0.0,
score = 0.0,
x = 0.0,
y = 0.0;
char c = 0;
for (; a < 200; a++) { /* loop however you like */
printf ("Enter no of Credits of the subject = ");
if (scanf ("%lf", &x) != 1) { /* validate EVERY input */
fprintf (stderr, "error: invalid input for 'x'.\n");
return 1;
}
empty_stdin(); /* empty stdin, your \n gimick doesn't work */
printf ("Enter the score for the subject = ");
if (scanf ("%lf", &y) != 1) {
fprintf (stderr, "error: invalid input for 'y'.\n");
return 1;
}
empty_stdin();
score = x * y; /* compute values each iteration */
ctot += x;
stot += score;
/* prompt for additional credits? */
printf ("add additional credits? (y/n): ");
if (scanf (" %c", &c) != 1) {
fprintf (stderr, "error: user canceled input.\n");
return 1;
}
empty_stdin();
if (c == 'n' || c == 'N') /* you can use 'q', but (y/n) is fine */
break;
}
printf ("\nGPA of the student = %f\n", stot/ctot);
return 0;
}
(can you figure out why if (scanf (" %c", &c) != 1) can only mean that the user canceled input?)
Example Use/Output
note: there are extraneous characters intentionally input below to provide example of how the simple additions to your code handle them safely. (try the input below with your original code and see what happens)
$ ./bin/credits_grades
Enter no of Credits of the subject = 3
Enter the score for the subject = 90
add additional credits? (y/n): y
Enter no of Credits of the subject = 4 (seemed like 40)
Enter the score for the subject = 80 (thank god!)
add additional credits? (y/n): y
Enter no of Credits of the subject = 3
Enter the score for the subject = 85
add additional credits? (y/n): n
GPA of the student = 84.500000
Look things over and let me know if you have further questions.
Initializing ctot and stot and re-positioning score=x*y your code will work . Try this edited code this works fine :-
#include <stdio.h>
void main()
{
double a = 0, x, ctot;
double y, stot;
char b, c = 'q';
double score;
ctot = 0; // initialize ctot and stot #ERROR1
stot = 0;
while (a < 200)
{
printf("\n Enter no of Credits of the subject = ");
scanf("%lf", &x);
printf("\n Enter the score for the subject = ");
scanf("%lf", &y);
getchar(); // to manage the addtional \n from scanf()
score = x * y; // computing score #ERROR2
scanf("%c", &b);
if (b == 'q')
{
break;
}
else
{
ctot += x;
stot += score;
a++;
}
}
printf("\n GPA of the student = %f", stot / ctot);
}
based on comments of #mch and #David C. Rankin
should modify the slot+=score to slot+=x*y
#include<stdio.h>
void main()
{
double a=0, x, ctot;
double y, stot;
char b, c='q';
double score=x*y;
while(a<200){
printf("Enter no of Credits of the subject = ");
scanf("%lf\n",&x);
printf("Enter the score for the subject = ");
scanf("%lf\n",&y);
scanf("%c\n",&b);
if(b=='q'){
break;
}else{
ctot+=x;
stot+=x*y;
a++;
}
}
printf("GPA of the student = %f\n", stot/ctot);
}
#include <stdio.h>
#include <math.h>
#define M_PI 3.14
int main(void)
{
// Declaring Variables
float time, p1, p2, p3, voltage, p3_num, p3_dem, epsilon;
int index, type;
// Asking user for time and index values into equation
printf("Please enter a time value: ");
scanf("%f", &time);
printf("Please enter an index value: ");
scanf("%d", &index);
// Calculate value for given time, part a, b, or c
printf("Do you want to run type a, b, or c?: ");
scanf("%d", &type);
char again = 'Y';
while (again == 'Y')
{
if (type == 'a') {
int going = 'Y';
while (going == 'Y')
{
// Different parts of formula to ensure accuracy
printf("Please enter an index value: ");
scanf("%d", &index);
p1 = ((3 / 2) - 12 / pow((M_PI), 2));
p2 = (1 / pow((double)(2 * index - 1), 2));
p3_num = ((2 * index - 1) * M_PI * time);
p3_dem = 3;
p3 = cos(p3_num / p3_dem);
voltage = p1 * p2 * p3;
printf("time = %f", time);
printf("index = %i", index);
printf("voltage = %f", voltage);
printf("Again? (Y/N)");
scanf("%c", &going);
}
}
}
}
There is more underneath, but this is the main bulk. What I am confused about is that none of this running, none. I start at the very beginning and comment out everything else, not even my print statement is running. What is wrong?
You should divide your program up into smaller function so you can test them individually.
For example here would be a function that reads in one integer.
int GetInteger(const char * msg)
{
//read up on c style formatting here is a source http://en.cppreference.com/w/c/io/fscanf
int i = 0;
printf("%s", msg);
scanf("%i", &i);
printf("Program confirms: %i\n", i);
return i;
}
This will help you down the road. Read up on SOLID principles and Test Driven Development.
I'm trying to learn C on my own, I have some previous experience in Matlab and Python. I'm trying to create a simple guessing game where you give a number, the computer guesses a number and you have to tell it if it's higher or lower. I've written some code, but it just doesn't work (try inputting 30, for example). The code is ugly, but I'm just trying to understand what's going on.
I've tried writing it using the case statement, but same results there.
Also, what is going on when you answer the y/n question with yy? The numbers go way up all of a sudden?
#include "stdio.h"
#include "stdlib.h"
int main(void) {
int a;
int i = 1;
int b = 50;
int temp;
int last = 0;
char ans = ' ';
printf("Enter value for computer to guess (0-100): ");
scanf("%d", &a);
while (a - b) {
printf("Is the number larger than %i (y/n): ", b);
scanf("%s", &ans);
if (ans == 'y') {
temp = b;
b = b + ((b + last) / 2);
last = temp;
} else {
temp = b;
b = b - ((b + last) / 2);
last = temp;
}
i++;
}
printf("Your number was: %i. Number of guesses was: %i \n", b, i);
return 0;
}
In your code
scanf("%s",&ans);
invokes undefined behavior as you're overrunning the allocated memory.
To use %s format specifier, you'll need an array as the argument (pointer to the first element of the array, to be specific).
However, in your case, changing
scanf("%s",&ans);
to
scanf(" %c",&ans); // note the space
is likely to solve the issue. Optionally, to handle the extra input, (like yyy), you can consider clearing the input buffer after reading each input, like
while (getchar() != '\n');
or likewise.
You probably want the computer to binary search for the answer and get there efficiently. You'll need to keep track of the upper and lower boundaries where you're searching. Try something like this;
int main(void){
int a;
int i = 1;
int b = 50;
int lower = 0;
int upper = 100;
char ans[256] = {0};
printf("Enter value for computer to guess (0-100): ");
scanf("%d", &a);
while (a-b) {
printf("Is the number larger than %i (y/n): ",b);
scanf("%s",ans);
if (ans[0] == 'y') {
lower = b;
b = b + ((upper-lower)/2);
printf("Last: %d - %d\n",lower, upper);
}
else {
upper = b;
b = b - ((upper-lower)/2);
printf("Last: %d - %d\n",lower, upper);
}
i++;
}
printf("Your number was: %i. Number of guesses was: %i \n",b,i);
return 0;
}
This is the problem.
char ans = ' ';
...
scanf("%s",&ans);
ans has only a single byte of memory, but you've asked scanf for a whole string. So it dutifully stuffs the whole string into the single byte of ans. Since this includes a null byte, even the input y or n will write an extra byte. yy writes three bytes.
This causes ans to silently overflow its memory wrecking havoc on adjacent variables. This is why yy messes with things, you're putting 3 bytes (2 characters plus a null byte) into 1 allocated byte overflowing by 2 bytes. It overwrites last with the character y which is the number 121. You can see this with a few debugging printfs.
printf("b = %d, last = %d\n", b, last);
printf("Is the number larger than %i (y/n): ",b);
scanf("%s",&ans);
printf("b = %d, last = %d\n", b, last);
Enter value for computer to guess (0-100): 30
b = 50, last = 0
Is the number larger than 50 (y/n): yy
b = 50, last = 121
Instead you want to use %c to read a single character. But that has its own problems, scanf("%d", &a) is leaving a newline on STDIN and scanf("%c", &ans) will read that newline first.
This is why scanf is a problem and should be avoided, it can leave unexpected input in the stream. There's lots of answers here on SO recommending against scanf. Instead use fgets or getline to read the whole line and then use sscanf to read the string. I prefer getline because it handles allocating line memory for you.
Here's a sketch of what to do.
char *line = NULL;
size_t linelen = 0;
printf("Enter value for computer to guess (0-100): ");
getline(&line, &linelen, stdin);
sscanf(line, "%d", &a);
printf("You entered %d\n", a);
printf("Is the number larger than %i (y/n): ",b);
getline(&line, &linelen, stdin);
sscanf(line, "%c", &ans);
switch(ans) {
case 'y':
...
break;
case 'n':
...
break;
default:
printf("I don't understand '%c', try again.\n", ans);
}
free(line);
I have to multiply digits by taking input from the user and when he enter 'n' it will produce the answer.
For example (2*3*2 = 12). But I manage to write the code for taking two inputs but can't find the way to take multiple inputs from user and produce the total answer. Here is the code;
void main (void)
{
float f1,f2;
float total;
int status1,status2;
printf("Enter first number to multiply:'n' to quit.\n ");
status1=scanf("%f",&f1);
printf("Enter another number to be multiply:'n' to quit.\n ");
status2=scanf("%f",&f2);
while (status1==1 && status2==1)
{
total=f1*f2;
status1=scanf("%1.0f",&f1);
status2=scanf("%1.0f",&f2);
}
printf("Multiplition Total = %1.0f",total);
getch();
}
You can use a while loop, as follows.
float prod = 1, f;
printf( "Enter the numbers, n to stop.\n" );
while( scanf( "%f", &f ) )
prod *= f;
printf( "product = %f\n", prod );
Tested:
#include <stdio.h>
int main()
{
int total = 1, factor = 1, success;
do
{
total *= factor;
printf("Enter integer number to multiply or 'n' to quit: ");
success = scanf("%d", &factor);
}
while (success);
printf("Multiplication Total = %d\n", total);
return 0;
}
And a piece of advice as you said you start your adventure with C:
Unless you have some specific reason to do otherwise, use double, not float.
However, in your question you asked for digits (integer) multiplication, so int is sufficient. If you can avoid floating point numbers, avoid them. They're much more complicated then integers and can let you in worse problems if you don't use them with caution.
You can refer to What Every Computer Scientist Should Know About Floating-Point Arithmetic.
This would do what you need and handles, 0, 1 or an unlimited number of inputs:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
float f1;
float total = 0;
printf("Enter number: ");
if (scanf("%f",&total))
{
for (;;)
{
printf("Enter number: ");
if (!scanf("%f", &f1))
{
break;
}
total *= f1;
}
}
printf("Multiplication Total = %f\n",total);
getch();
return 0;
}
It keeps a running total as values are entered but it stops on first invalid input, not just when n is entered.
Untested:
float f, p = 1;
printf ("Enter a number: ");
fflush (stdout);
while (scanf("%f", &f) != EOF)
{
p *= f;
printf ("Enter another number: ");
fflush (stdout);
}
printf ("Product: %f\n", p);