Recall the char function - c

I'm very new to programming, and I'm doing a simple bot in C, that has a calculator function. I'm having some trouble in this piece of code:
char operation = get_char("Insert the mathematical operation: ");
float x = get_float("X: ");
float y = get_float("Y: ");
if (operation == 43)
{
float result = (x + y);
int rresult = round(result);
printf("X + Y = %i\n", rresult);
string confirmation = get_string("Need to do something more? ");
if (strcmp(confirmation, "Y") == 0)
{
return operation;
}
As you can see, this calculator ask the user for a char (*, /, + or - [its everything defined in the other parts of the code, I will not post it here just to be brief] that defines the math operation and then, after doing the calculation and printing the result, asks the user if he wants to do more calculations. If the answer is "Y" (yes), I want to restart this piece of code, asking for the char and the floats, and doing everything. I want to know the simplest way to do this, without making the code looks bad designed.
Also, I'm using CS50 IDE.

I don't have CS50, therefore, plain C. The construct you might want to use is a do-while loop.
#include <stdio.h>
#include <math.h>
char get_char(char * msg) {char c; printf("%s", msg); scanf(" %c", &c); return c;}
float get_float(char * msg) {float f; printf("%s", msg); scanf(" %f", &f); return f;}
int main() {
char confirmation = 'n';
do {
char operation = get_char("Insert the mathematical operation: ");
float x = get_float("X: ");
float y = get_float("Y: ");
if (operation == '+') {
float result = (x + y);
printf("Result in float: %f\n", result);
int rresult = round(result);
printf("X + Y = %i\n", rresult);
}
confirmation = get_char("Need to do something more [y/n]? ");
} while (confirmation == 'y');
return 0;
}
$ gcc -Wall dowhile.c
$ ./a.out
Insert the mathematical operation: +
X: 0.11
Y: 0.88
Result in float: 0.990000
X + Y = 1
Need to do something more [y/n]? y
Insert the mathematical operation: +
X: 0.1
Y: 0.1
Result in float: 0.200000
X + Y = 0
Need to do something more [y/n]? n
$

Related

Not getting output, no errors found ( c language)

C code for calculating simple interest
#include <stdio.h>
int main()
{
float principle, rate, years;
float simpleInterest = (principle * rate * years)/100;
printf("Enter the principle");
scanf("%f", &principle);
printf("Enter the rate");
scanf("%f", &rate);
printf("Enter the years");
scanf("%f", &years);
printf("The simple interest is %f", simpleInterest);
}
C variables are not mathematical variables: they do not express a relationship:
int y = x + 1; // this does NOT mean that `y` is always equal to `x + 1`
Instead, statements are executed from top to down, and when a variable name comes up in the code, the C language will read its contents[1]. Therefore:
int x = 5;
// now x == 5
int y = x + 1;
// now x == 5 and y == 6
x = 8;
// now x == 8 and y == 6
That means that your code should be:
#include <stdio.h>
int main(void) // NOTE: use `int main(void)` instead of `int main()`
{
float principle, rate, years;
printf("Enter the principle");
scanf("%f", &principle);
printf("Enter the rate");
scanf("%f", &rate);
printf("Enter the years");
scanf("%f", &years);
float simpleInterest = (principle * rate * years) / 100.0f;
printf("The simple interest is %f\n", simpleInterest);
return 0;
}
NOTES:
[1] = not always true, because of short circuiting when using operators like && and ||, and because operators like sizeof do not evaluate the expressions. But this is beyond the scope of my answer.

Why scanf is not working in functions using C programming? [duplicate]

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.

Storing arithmetic operators in an array in C?

I am just wondering if it is possible to store the basic arithmetic operators (+, -, *, /) inside variables in C. The reason that I need to do this is because I am trying to build a basic calculator program that accepts up to 5 numbers and can do any of these operations on them. Right now the only way that I have been able to come up with to do this is to store the operators inside a char array and then iterate through it using for loops and switch statements to decide what operator to use for each step. It's pretty clunky and doesn't actually work right now and I am not sure why. Also even if it did work, it wouldn't follow order of operations which I need it to do as well.
This is an example of the output of my program:
Enter a number: 4
Enter an operator (+, -, *, /, or =): +
Enter a number: 8
Enter an operator (+, -, *, /, or =): -
Enter a number: 7
Enter an operator (+, -, *, /, or =): *
Enter a number: 9
Enter an operator (+, -, *, /, or =): /
Enter a number: 2
4.00 + 8.00 - 7.00 * 9.00 / 2.00
0.500000
-6.500000
-6.500000
-3.250000
-3.250000
Result: -3.25
[Finished in 24.13s]
The first 9 lines are just taking the input for the numbers and operators, the 10th line prints out the numbers and operators entered in order, the 11th - 15th lines are supposed to print out the result after each operation which you can see are all incorrect, and the final line prints out the result. What do you think might be causing the math to be incorrect?
Here is my code at the moment:
#include <stdio.h>
#include <stdlib.h>
int main() {
double nums[5];
char operators[5];
double result;
int i = 0;
while ((i <= 4) && (operators[i - 1] != '=')) {
/* Getting the user's input */
printf("Enter a number: ");
scanf("%lf", &nums[i]);
if (i == 4) {
operators[4] = '=';
} else {
printf("Enter an operator (+, -, *, /, or =): ");
scanf(" %c", &operators[i]);
}
i++;
}
printf("%.2f %c %.2f %c %.2f %c %.2f %c %.2f\n", nums[0], operators[0], nums[1], operators[1], nums[2], operators[2], nums[3], operators[3], nums[4]);
for (i = 0; i <= 4; i++) {
/* Doing the math */
if (i == 0) {
/* Getting the value of the first two numbers */
switch(operators[i]) {
case '+' :
result = nums[0] + nums[1];
case '-' :
result = nums[0] - nums[1];
case '*' :
result = nums[0] * nums[1];
case '/' :
result = nums[0] / nums[1];
}
printf("%f\n", result);
} else {
/* Iterating through the rest of both arrays and
continuing to perform operations on the result */
switch(operators[i]) {
case '+' :
result = result + nums[i + 1];
case '-' :
result = result - nums[i + 1];
case '*' :
result = result * nums[i + 1];
case '/' :
result = result / nums[i + 1];
}
printf("%f\n", result);
}
}
// Printing out the answer rounded to 2 decimal points
printf("Result: %.2f", result);
return 0;
}
So just to re-iterate my question, is there a way that I could store the operators in a variable as operators instead of chars, which would remove the need for all of the loops, if statements, and switch statements, and if not, what changes should be made to make my code work properly?
P.S. I am only just learning C right now so suggestions for how I should be formatting my code are welcome too.
First the bugs:
while ((i <= 4) && (operators[i - 1] != '=')) {
On the first iteration of this loop i is 0 so operators[i - 1] attempts to read before the start of the array. Reading outside of array bounds is undefined behavior.
The incorrect values you're getting is because there's no break statement between each of your switch cases. Without that, the code "falls through" to the next case. So if the operation is subtraction you do that, then multiplication, then division.
Regarding the operators, you can create functions to encapulate each operator, each with the same signature (i.e. return type and number/type of parameters) along with a matching typedef. Then you can have an array of pointers to these functions, and set them to point to the proper function.
Also, you don't need to have a special case for the first set of operators. Just start from index 1 instead of 0 and initialize the result to the first value.
#include <stdio.h>
#include <stdlib.h>
double op_add(double x, double y)
{
return x + y;
}
double op_sub(double x, double y)
{
return x - y;
}
double op_mul(double x, double y)
{
return x * y;
}
double op_div(double x, double y)
{
return x / y;
}
typedef double (*op_type)(double, double);
int main() {
double nums[5];
char operator;
op_type operators[5];
double result;
int i = 0;
while (i < 5) {
/* Getting the user's input */
printf("Enter a number: ");
scanf("%lf", &nums[i]);
if (i == 4) {
operators[i] = NULL;
} else {
printf("Enter an operator (+, -, *, /, or =): ");
scanf(" %c", &operator);
switch(operator) {
case '+' :
operators[i] = op_add;
break;
case '-' :
operators[i] = op_sub;
break;
case '*' :
operators[i] = op_mul;
break;
case '/' :
operators[i] = op_div;
break;
default :
operators[i] = NULL;
break;
}
}
if (!operators[i]) break;
i++;
}
result = nums[0];
for (i = 1; i < 5; i++) {
if (operators[i-1]) {
result = operators[i-1](result, nums[i]);
printf("%f\n", result);
} else {
break;
}
}
// Printing out the answer rounded to 2 decimal points
printf("Result: %.2f", result);
return 0;
}

My code is not running in Xcode, scanner issue

#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.

How to make an answer a floating number or integer depending on the number entered?

Currently working on an assignment and a bit stuck. We are to convert a temperature from Celsius to Fahrenheit. The final answer should output a floating point number if the answer is a decimal, or a integer if it's a whole number. I have it set up to give me the floating point number, but when I enter a number, say '98.6', I'll get 37.00000 rather than 37. Been at it for a few hours trying to combat it on my own but I've run out of ideas. Thanks for the assistance!
int main(void)
{
float ftemp;
float ctemp;
printf ("Enter a temperature in Fahrenheit: ");
scanf ("%f", &ftemp);
ctemp = (100.0 / 180.0) * (ftemp - 32);
printf ("In Celsius, your temperature is %f!\n", ctemp);
return 0;
}
There really isn't a good way to do this as you have described. What it really sounds like you want is better string formatting. Try using %g instead of %f in your printf (per this post).
e.g.
printf ("In Celsius, your temperature is %g!\n", ctemp);
Now, if you are hell bent on getting it to use an integer, the closest you can come is with:
int main(void)
{
float ftemp;
float ctemp;
int ctempi;
printf ("Enter a temperature in Fahrenheit: ");
scanf ("%f", &ftemp);
ctemp = (100.0 / 180.0) * (ftemp - 32);
ctempi = (int)ctemp;
if(ctemp == ctempi) {
printf("In Celsius, your temperature is %d\n", ctempi);
} else {
printf ("In Celsius, your temperature is %f!\n", ctemp);
}
return 0;
}
You are printing your number as a float, to print it as an integer:
printf ("In Celsius, your temperature is %d!\n", (int) ctemp);
It uses the d conversion specifier for decimal print and the argument is casted to int as %d requires an int.
One thing that's tricky about floating point numbers is that they're not exact. A number that can be expressed in decimal without repeating digits might have repeating digits in binary.
So you need to check if the result is an integer, however due to the imprecise nature of floating point something like (1.0 / 3.0 * 3) == 1 might evaluate to false. So you need to see if it's within some threshold of an integer.
if (fabs(ctemp - roundf(ctemp)) < 0.0001) {
// result is close enough to an integer, so print as integer
printf ("In Celsius, your temperature is %d!\n", (int)ctemp);
} else {
// result is not an integer, so print as a float
printf ("In Celsius, your temperature is %f!\n", ctemp);
}
Read input as a string and test for integer-ness.
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
struct dual {
char type;
union {
int i;
float f;
} u;
} dual_T;
dual_T GetNumber(void) {
dual_T number;
float f;
char buf[100];
if (fgets(buf, sizeof buf, stdin) == NULL) {
number.type = 'n';
return number;
}
// test for float - sample code possibility
int n = 0;
sscanf(buf, "%f %n", &f, &n);
bool f_possible = n > 0 && *n == 0;
// test for int - sample code possibility
n = 0;
sscanf(buf, "%i %n", &number.u.i, &n);
bool i_possible = n > 0 && *n == 0;
if (f_possible) {
if (i_possible) {
// If fits as an `int`, go with `int` as likely higher precision.
if (f >= INT_MIN && f <= INT_MAX) {
number.type = 'i';
return number;
}
}
number.type = 'f';
number.u.f = f;
} else {
if (i_possible) {
number.type = 'i';
} else {
number.type = 'n'; // none
}
}
return number;
}

Resources