I am trying to write a program that calculates the length of one side of a triangle with the help of the Pythagoras equation (c²=a²+b²). The user must have the option to choose what side he want to calculate, this is what I have tried:
#include <conio.h>
#include <stdio.h>
#include <math.h>
// Pitagora:
// c=sqrt(pow(a,2)+pow(b,2));
// a=sqrt(pow(c,2)-pow(b,2));
// b=sqrt(pow(c,2)-pow(a,2));
int cateta(int x, int y){
int cat;
printf("Dati marimea lui:");
scanf("%d", &x);
printf("Dati marimea lui:");
scanf("%d", &y);
cat=sqrt(pow(x,2)-pow(y,2));
return cat;
}
int main(){
int a,b,c;
char l;
printf("Ce latura doriti sa aflati?");
printf("\n c : ipotenuza\n a : cateta alaturata\n b : cateta opusa\n");
printf("Introduceti litera laturei respective : ");
scanf("%s", &l);
if (l == a){
a=cateta(c,b);
printf("Marimea catetei alaturate este: %d", a);
}
else if (l == b){
b=cateta(c,a);
printf("Marimea catetei opuse este: %d", b);
}
else {
c=sqrt(pow(a,2)+pow(b,2));
printf("Marimea ipotenuzei este: %d", c);
printf("\n");
}
getch ();
return 0;
}
But, for some reason when I give a value of a to the variable &l the program displays the content of this piece of code: printf("Marimea ipotenuzei este: %d", c); instead of scaning the value of x and y, and terminates. Here is a picture with the result: https://www.dropbox.com/s/wzk3osw1t8729et/Untitled.png?dl=0
you are using %s in scanf() for a character type variable, instead use this
scanf(" %c", &l);
First, u need to change the scanf statement to scanf( "%c",&l);
Now the variable l contains the character entered by user.
Next, during comparison change the if condition to if(l=='a') , if( l=='b') as a and b are character literals.
With this changes, the program should work!
Happy coding!!
Related
This is literally my first lines of code in C, so it's really basic.
The code is this:
#include<stdio.h>
int main()
{
int l, b, ar, pr;
printf("Enter the length of the rectangle");
scanf("%d", l);
printf("Enter the breadth of the rectangle");
scanf("%d", b);
ar = l * b;
pr = 2 * (l + b);
printf("\n Area of Rectangle is: %d", ar);
printf("\n Perimeter of Rectangle is: %d", pr);
}
It starts running properly, outputs "Enter the length of the rectangle", but when I input a number, it just stops and I don't get to input the second value.
What am I missing?
You have to pass pointers to the variables to get the values instead of the values in the variables.
You should use unary & operators to get pointers like this:
scanf("%d", &l);
Note that you don't need & to read strings because arrays are automatically converted to pointers to the first element (except for some cases, including when used as an operand of unary & operator).
char str[10];
scanf("%9s", str);
Corrected code
#include<stdio.h>
int main()
{
int l, b, ar, pr;
printf("Enter the length of the rectangle");
scanf("%d", &l);
printf("Enter the breadth of the rectangle");
scanf("%d", &b);
ar = l * b;
pr = 2 * (l + b);
printf("\n Area of Rectangle is: %d", ar);
printf("\n Perimeter of Rectangle is: %d", pr);
}
This question already has answers here:
Simple C scanf does not work? [duplicate]
(5 answers)
Closed 1 year ago.
I wrote this C program using 2 functions, but in this first case grade() is not prompting for the input:
#include <stdio.h>
int motivQuote();
char grade();
void main()
{
int x;
char y, z;
printf("Programmer-defined Function Type 2\n");
x = motivQuote();
printf("Returned value is %d\n\n", x);
printf("Expected grades this semester:\n");
printf("Subject1: ");
y = grade();
printf("\nReturned value is %c\n", y);
}
int motivQuote()
{
int n = 0;
printf("Select quote (1 or 2):");
scanf_s("%d", &n);
if (n == 1)
printf("\n~ Robert Collier ~\n\t\"Success is the sum of small efforts, repeated day in and day out.\"\n");
if (n == 2)
printf("\n~ David Bly ~\n\t\"Striving for success without hard work\n\tis like trying to harvest where you haven’t planted.\"\n");
return n + 2;
}
char grade()
{
char grade = 0;
scanf_s("%c", &grade, 1);
return grade;
}
And here in the second case, grade() prompts for the input only in the second call, but the first one is not working:
#include <stdio.h>
int motivQuote();
char grade();
void main()
{
int x;
char y, z;
printf("Programmer-defined Functions\n");
x= motivQuote();
printf("Returned value is %d\n\n", x);
printf("Expected grades this semester:\n");
printf("Subject1: ");
y= grade();
printf("\nSubject2: ");
z= grade();
printf("Returned values are %c and %c\n", y, z);
}
int motivQuote ()
{
int n = 0;
printf("Select quote (1 or 2):");
scanf_s("%d", &n);
if (n==1)
printf("\n~ Robert Collier ~\n\t\"Success is the sum of small efforts, repeated day in and day out.\"\n");
if (n==2)
printf("\n~ David Bly ~\n\t\"Striving for success without hard work\n\tis like trying to harvest where you haven’t planted.\"\n");
return n+2;
}
char grade()
{
char grade = 0;
scanf_s("%c", &grade,1);
return grade;
}
Can anyone tell me what's the reason please?
Use scanf(" %c",&grade,1); with a space before %c. This will solve the problem.
I am writing a piece of code to ask for two specific points in the format P0 x y.
If the user types in Q then the program terminates, for some reason I have trouble outputting the user input (P0 x y) into an output. When I try to run the code and type P0 2 3 it says I have chosen points 0 2.00 3.00.
While the desired output is P0 2 3.
#include <stdio.h>
void main() {
float a, b;
char Q, P, input;
printf("");
scanf("%c", &input);
if (input == 'Q') {
printf("quitting program");
return (0);
} else {
scanf("%c" "%f" "%f", &input, &a, &b);
printf("you have chose points: %c %f %f", input, a, b);
}
return (0);
}
Because you use two scanf. First scanf reads P then second scanf read 0 from command line (from stdin). So after second scanf, input = '0'. This is reason why your program prints 0 2.00 3.00
If you want to print out P0 you have to use string, for example the example below:
#include <stdio.h>
int main()
{
float a, b;
char Q, P, input;
char point[3] = {'\0'};
scanf( "%c" , &input);
point[0] = input;
if(input=='Q')
{
printf("quitting program");
return 0;
}
else
{
scanf( "%c" "%f" "%f", &input, &a, &b);
point[1] = input;
printf("you have chose points: %s %f %f",point, a, b);
}
return 0;
}
As the other answer also mentions, when checking for Q in input, the input byte is consumed. The C standard library provides a fix for this specific problem: you can "return" the consumed byte to the input device (keyboard buffer), and later retry reading from input.
The function is ungetc. It requires quite specific syntax (you should "unget" the same value as was just read; also you must use stdin to specify that you are working with keyboard) and only works for one byte, exactly as you need.
Here is your code with my updates and comments.
#include <stdio.h>
int main()
{
float a, b;
char Q; // only used for checking the "quit" condition
char input[10]; // assuming 9 characters + terminating byte is enough
scanf("%c", &Q);
if(Q=='Q')
{
printf("quitting program");
return (0);
}
else
{
ungetc(Q, stdin); // return one byte to the input device
scanf( "%s" "%f" "%f", input, &a, &b); // "%s" read from the input as string now
printf("you have chose points: %s %f %f",input, a, b);
}
return 0;
}
I have a requirement to get two integers and add and print the added value. I wrote a working program. Another requirement is to check whether the input value is other than integer and if it is other than integer, without closing the program, it should again ask for the inputs.
C Code
#include <stdio.h>
void main()
{
int a,b,c;
printf("This is a Addition program");
printf("\n Enter value of a:");
scanf("%d",&a);
printf("\n Enter value of b:");
scanf("%d",&b);
c=a+b;
printf("\n The added value is %d",c);
}
Here's some code that will completely fulfil your requirement. Yesterday David C Rankin posted an answer to the same basic question in Stack Overflow.
This code is basically what David provided:
#include <stdio.h>
static int getInt(const char *prompt)
{
int value;
char c;
while(printf("%s",prompt) && scanf("%d", &value) !=1)
{
do { c = getchar(); } while ( c != '\n' && c != EOF ); // flush input
printf ("Invalid Entry, Try Again...\n");
}
return value;
}
int sum(int a , int b) { return ( a + b ); }
int main(){
int a , b;
a = getInt("Please enter a number");
b = getInt("Please enter a number");
printf("Sum is :%d" , sum(a,b));
}
The function getInt check the input and yells for the wrong input.
This program will do what you want
#include<stdio.h>
int main() //use int not void
{
int a,b,c;
printf("This is a Addition program");
printf("\n Enter value of a:");
while(scanf("%d",&a)==0)
{
printf("\n Invalid input.Try again:");
getchar(); // clear the previous input
}
printf("\n Enter value of b:");
while(scanf("%d",&b)==0)
{
printf("\n Invalid input.Try again:");
getchar(); // clear the previous input
}
c=a+b;
printf("\n The added value is %d",c);
return 0; // because main returns int
}
scanf returns the number of successfully read items, so it will return 1 in your case if a valid value was entered. If not, an invalid integer value was entered and scanf will return 0.
Use fgets()/sscanf()/strto...() rather than scanf().
scanf() parses and performs input in the same function and does not well handle unexpected input. Use fgets() for user input and then scan/parse.
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdio.h>
int getint(const char *prompt) {
char buf[sizeof(int) * CHAR_BIT];
while (1) {
fputs(prompt, stdout);
fflush(stdout);
if (fgets(buf, sizeof buf, stdin) == NULL) {
// sample handling of unexpected input issue.
// Value to return of EOF or IO error
return INT_MIN;
}
/// strtol() is another option
int i, n;
// " %n" notes offset of non-white-space after the numebr.
if (1 == sscanf(buf, "%d %n", &i, &n) && buf[n] == '\0') {
return i;
}
}
}
int main(void) {
int a, b, c;
printf("This is a Addition program");
a = getint("\n Enter value of a:");
b = getint("\n Enter value of b:");
c = a + b;
printf("\n The added value is %d", c);
return 0;
}
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
Hi I have written a c program that reads in 2 values then swaps them and prints the new values except the second value keeps showing 0. For example it you enter 10 for 'a' and 8 tor 'b', then a will be 8 but b will be 0. Does anyone know the solution to fix this? Here is the code:
#include <stdio.h>
int getData()
{
int a, b;
printf("Enter first number: ");
scanf("%d", &a);
printf("Enter second number: ");
scanf("%d", &b);
return(a, b);
}
void swapValues(int a, int b)
{
printf("The value of a is: %d", b);
printf("\nThe value of b is: %d", a);
return;
}
int main()
{
int a, b = getData();
swapValues(a, b);
return(0);
}
return (a, b);
doesn't do what you think it does, it's a misapplication of the comma operator.
The expression op1, op2 evaluates both op1 and op2 but gives you the value of op2. So it's not passing back a couple of values (although some languages like Python can do this sort of thing).
Similarly,
int a, b = getData();
won't grab the mythical two values returned from getData(). Rather it will set a to an indeterminate value and set b based on the single value returned from the function.
I would be looking at something like this:
#include <stdio.h>
int getData (char *which) {
int val;
printf ("Enter value for %s: ", which);
scanf("%d", &val);
return val;
}
void swapValues (int a, int b) {
printf("The swapped value of a is: %d\n", b);
printf("The swapped value of b is: %d\n", a);
}
int main (void) {
int a = getData ("a");
int b = getData ("b");
swapValues(a, b);
return 0;
}
You should also keep in mind that, if you actually want to swap the variables a and b and have that reflected back to main(rather than just print them as if they've been swapped), you'll need to pass pointers to them and manipulate them via the pointers.
C is a pass-by-value language meaning that changes to function parameters aren't normally reflected back to the caller. That would go something like this:
void swapValues (int *pa, int *pb) {
int tmp = *pa;
*pa = *pb;
*pb = tmp;
}
:
swapValues (&a, &b);
// a and b are now swapped.
You have unnecessarily complicated the whole thing.For one, something like return(a,b) is absurd in C.Further, if you intend to swap, why are you passing b as argument for the printf() meant to print 'a' and passing a to the printf() of 'b'?Anyways,here's a modified code that keeps it simple and gets the job done.
#include <stdio.h>
void swapValues()
{
int a, b,tem;
printf("Enter first number: ");
scanf("%d", &a);
printf("\nEnter second number: ");
scanf("%d", &b);
tem=a;
a=b;
b=tem;
printf("\nThe value of a is: %d", a);
printf("\nThe value of b is: %d", b);
}
int main()
{
swapValues();
return(0);
}
First of all you can't return more than one value in C. The way around that is to return a struct or pass the values address.
void getData(int *a,int* b)
{
//int a, b;
printf("Enter first number: ");
scanf("%d", a); // look here you passed the address of a to scanf
// by doing that scanf can write to a
printf("Enter second number: ");
scanf("%d", b);
//return(a, b);
}
The old main:
int main()
{
int a, b = getData(); // b gets the return value from getData()
// but a is still uninitialized
//to call the new function you have to do the following
int a,b;
getData(&a,&b);
swapValues(a, b);
return(0);
}
You cannot return multiple values from a C function. I'm not even sure why the statement return(a, b) compiles.
If you want to return more than value from a function you should either put them into an array or a structure. I'm going to use a structure to demonstrate one way to do this correctly. There are many ways to do this, but this one modifies you code the least.
struct TwoNums{
int a;
int b;
};
TwoNums getData()
{
/* This creates a new struct of type struct TwoNums */
struct TwoNums nums;
printf("Enter first number: ");
scanf("%d", &(nums.a));
printf("Enter second number: ");
scanf("%d", &(nums.b));
return(a, b);
}
void swapValues(int a, int b)
{
printf("The value of a is: %d", b);
printf("\nThe value of b is: %d", a);
return;
}
int main()
{
/* Get the whole structure in one call */
struct TwoNums nums = getData();
/* Call the swap function using fields of the structure */
swapValues(nums.a, nums.b);
return 0;
}
The first:
getData() function is written incorrectly.
You can not return more than one parameter from the function in C. So you can to separate data reading, or use pointers as below:
void getData(int* a, int* b) {
printf("Enter first number: ");
scanf("%d", a);
printf("Enter second number: ");
scanf("%d", b);
}
In main()
int a, b;
getData(&a, &b);
The second:
swapValues(int a, int b) does not swap the data.
More correct:
void swapValues(int* a, int* b) {
int tmp = *a;
*a = *b;
*b = tmp;
}
without using temporary variable.
So try this code
#include <stdio.h>
int swape()
{
int a,b;
printf("Enter first number: ");
scanf("%d", &a);
printf("Enter second number: ");
scanf("%d", &b);
a=a+b;
b=a-b;
a=a-b;
printf("The value of a is: %d", a);
printf("\nThe value of b is: %d", b);
}
int main()
{
swape();
return(0);
}