after making progress and rewriting most of the code for our calculator project, i run into a problem.
as the title suggest i need help with reinitializing the variable after loop or in every loop.
problem:
It should to like this:
as you can see instead of prompting an error it still calculate, suggesting that the inputed int was stored in my variable. which i maybe wrong or something but if i cannot fix these i make more progress.
Here is the code:
#include <stdio.h>
#include <stdbool.h>
//bool function
bool isInteger(double val)
{
int truncated = (int)val;
return (val == truncated);
}
int main(int argc, char *argv[])
{
//local variable
double a, b;
char operation, option = 'y';
//loop
while(option == 'y' || option == 'Y')
{
//system("cls");
printf("Enter number and operator to solve:\n\nExapmple [a + b][a - b][a * b][a / b]\n");
scanf("%lf %c %lf", &a, &operation, &b);
// nested if
if(isInteger(a) && isInteger(b))
{
if(operation == '+')
{
printf("Result: %.1lf\n\n", a + b); //ouput result
}
else if(operation == '-')
{
printf("Result: %.1lf\n\n", a - b); //ouput result
}
else if(operation == '*')
{
printf("Result: %.1lf\n\n", a * b); //ouput result
}
else if(operation == '/')
{
printf("Result: %.1lf\n\n", a / b); //ouput result
}
else
{
//output error
printf("Invalid Operater!\n");
}
}
else
{
//output error
printf("Input is not a digit!\n");
}
//output selection
printf("Do you want to retry [y]/[n]?");
option = getch(); //not recommended but just a small project
//scanf("%c", &option); -- stops the loop
} //end loop
}
In your second example (i.e., second time around), this line
scanf("%lf %c %lf", &a, &operation, &b);
tries to read an a into a double which will cause scanf to fail and return early.
Check the documentation of scanf and you'll see that it returns the number of values read and will set errno on failure. These must be checked before a, operation and b can be safely used.
Related
I have been trying to program a tool, where I take input from the user if its a circle or square or rectangle and accordingly it will take the measurement inputs and print out the area for the same. But its not working, please help me with what are the problems with my code and how can i get it to work?
#include<stdio.h>
#include<math.h>
float square(float side);
float circle(float rad);
float rect(float a,float b);
int main(){
char lol;
printf("press s for square\n c for circle\n r for rectagle\n");
scanf("%c ", &lol);
if(lol == 's')
{
int t;
printf("enter side measurement");
scanf("%d", &t);
printf("the area is %f", square(t));
}
if(lol == 'c');
{
int r;
printf("enter radius of circle");
scanf("%d", &r);
printf("the area is %f", circle(r));
}
if (lol == 'r')
{
int m,n;
printf("enter 2 sides ");
scanf("%d %d", &m,&n);
printf("the area is %f", rect(m,n));
}
return 0;
}
float square(float side){
return side*side;
}
float circle(float rad){
return 3.14* rad*rad;
}
float rect(float a,float b){
return a*b;
}
Screenshot of execution
You want to remove the trialing ' ' in the first scanf(), and remove the ; after the if statement.
If main() is last you often can get away with not specifying prototypes for small programs like this. Added error checking of scanf(). Prefer if-else-if when the conditions are mutually exclusive, or as here a switch statement so you don't need to repeat the lol == . Prettied up the prompts a bit (colons, newlines), and sorted both the menu and matching implementation. It makes it easier for end-users and easier to navigate for anyone working on the code. math.h defined the constant M_PI if __USE_XOPEN is set. It's better to use a constant than hard-coding the 3.14 value in circle().
#define __USE_XOPEN
#include <math.h>
#include <stdio.h>
float circle(float rad) {
return M_PI * rad * rad;
}
float rect(float a, float b) {
return a * b;
}
float square(float side) {
return side * side;
}
int main(void) {
printf("press:\n"
" c for circle\n"
" r for rectangle\n"
" s for square\n"
);
char lol;
if(scanf("%c", &lol) != 1) {
printf("scanf failed\n");
return 1;
}
switch(lol) {
case 'c': {
printf("enter radius of circle: ");
int r;
if(scanf("%d", &r) != 1) {
printf("scanf failed\n");
return 1;
}
printf("the area is %f\n", circle(r));
break;
}
case 'r': {
printf("enter 2 sides: ");
int m, n;
if(scanf("%d %d", &m,&n) != 2) {
printf("scanf failed\n");
return 1;
}
printf("the area is %f\n", rect(m,n));
break;
}
case 's': {
printf("enter side measurement: ");
int t;
if(scanf("%d", &t) != 1) {
printf("scanf failed\n");
return 1;
}
printf("the area is %f\n", square(t));
break;
}
default:
printf("invalid selection %c\n", lol);
}
}
Im making a calculator with A LOT of functions, Im not nearly done with the functions. But I thought, I want the program active after returning me the value I asked for. My logic was to put it into a while loop, but clearly my idea and how I put it are not equal. Or maybe my logic doesnt work in this case. Anyway, imagine I ask the program how much its 2+2 and it returns me 4. Done, but I want it to ask me again for another operation, how can I do that?
Im really new with this stuff, so thanks for the help.
To resume the code below. I ask for a value, then scan it, then ask for a operator, then I ask wether if the user want to continue or not, if he says yes thats the condition for the loop ---> while(condition != 'yes' );{
And if not, just end the program. And I putted the operations inside the loop.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int input;
double sinus;
int op;
printf(" What function do you want to use? \n \n --------------------------------------- \n");
printf(" BASIC OPERATIONS --> type 1 \n --------------------------------------- \n");
printf(" TRIGONOMETRIC FUNCTIONS \n sin --> type 2 \n cos --> type 3 \n tan --> type 4 \n arcsin --> type 5 \n arccos --> type 6 \n arctan --> type 7 \n --------------------------------------- \n");
scanf("%d", &op);
char condition[5];
printf("Stop? Type: yes or no");
scanf("%s", &condition);
while(condition != 'yes' );{
if (op == 1) {
double val1;
char op1;
double val2;
printf("Please type a number: \n" );
scanf("%lf", &val1);
printf("Please type an operator: \n" );
scanf(" %c", &op1);
printf("Please type another number: \n" );
scanf("%lf", &val2);
if (op1 == '+') {
printf("%f \n", val1 + val2);
}
if (op1 == '-') {
printf("%f \n", val1 - val2);
}
if (op1 == '*') {
printf("%f \n", val1 * val2);
}
if (op1 == '/') {
printf("%f \n", val1 / val2);
}
}
else if (op == 2) {
double arg;
printf("Please type the argument of sin(x) \n");
scanf("%lf", &arg);
printf("The value is %f", sin(arg));
}
else if (op == 3) {
double arg;
printf("Please type the argument of cos(x) \n");
scanf("%lf", &arg);
printf("The value is %f", cos(arg));
}
else if (op == 4) {
double arg;
printf("Please type the argument of tan(x) \n");
scanf("%lf", &arg);
printf("The value is %f", tan(arg));
}
else if (op == 5) {
double arg;
printf("Please type the argument of arcsin(x) \n");
scanf("%lf", &arg);
printf("The value is %f", asin(arg));
}
else if (op == 6) {
double arg;
printf("Please type the argument of arccos(x) \n");
scanf("%lf", &arg);
printf("The value is %f", acos(arg));
}
else if (op == 7) {
double arg;
printf("Please type the argument of arctan(x) \n");
scanf("%lf", &arg);
printf("The value is %f", atan(arg));
}
else {
printf("%d", 0);
}
}
}
Sorry for too many to read:((( Im not experienced with forums.
The following example will give you an idea how things can be repeated based on input.
check how strcmp is done,that way you are doing is wrong.
Also consider using switch for handling multiple cases of input and their operations.
#include<stdio.h>
#include <string.h>
#include <ctype.h> // isspace
int main() {
char choice[] = "Yes";
do{
int i = 0;
/**
* implement all you want here
*/
printf("Enter Yes to repeat, to exit enter any other non blank string\n");
while(isspace(choice[i] = getchar()));
while((choice[++i] = getchar()) != '\n');
choice[i] = '\0';
printf("choice = %s, i = %d\n", choice, i);
}while(!strcmp(choice,"Yes") );
return 0;
}
I am trying to check if the user inputs y or something else.
I have tried creating a string and looping through what the user inputs, but that doesn't work.
char answer[] = "n";
for(int i = 0; i < sizeof(answer)/4; i++) {
if(answer[i] == "y") {
calculatorPrompt();
} else if(answer[i] === "n") {
printf("Okay, bye!");
System(100);
}
}
This is my code (I'm sure it crashes on the if statement):
printf("Thanks for that\nDo you want a calculator?(y/n)");
char answer = 'n';
scanf("%s", answer);
if(answer == 'y') {
calculatorPrompt();
} else if(answer == 'n') {
printf("Okay bye!");
Sleep(100); //wait for 100 milliseconds
}
calculatorPrompt() function:
void calculatorPrompt() {
int a = 0;
int b = 0;
int sum = 0;
printf("Enter your first number: ");
if(scanf("%d\n", a) != 1) {
checkNumber();
} else {
printf("Enter your second number: ");
if(scanf("%d\n", b) != 1) {
checkNumber();
} else {
sum = calculate(a, b);
printf("Your answer is: %d", sum);
}
}
}
calculate() function:
int calculate(int a, int b) {
return a + b;
}
checkNumber() function:
void checkNumber() {
printf("Really? You didn't enter a number... Now exiting..");
return;
}
I have included <windows.h> <stdio.h> and <stdbool.h>
I'm also confused as to why it crashes.
The return value of the program is -1,073,741,819.
You have multiple issues with scanf() statements in the code :
in calculatorPrompt() funtion of your code, you use :
if(scanf("%d\n", a) != 1) //wrong : sending variable as argument
This is wrong because you need to send address of the variable as the argument not the variable itself as argument.
if(scanf("%d", &a) != 1) //correct : sending address as argument
similarly change while scanning other integers in the code.
here,
char answer = 'n';
scanf("%s", answer);
As you are using the wrong format specifier, this invokes Undefined behavior.
here since answer is a char so, instead use :
scanf(" %c", &answer); //space to avoid white spaces
and as I've already suggested in the comments :
You use i < sizeof(answer)/4 in the for loop
No! it must be i < sizeof(answer), as in a string every element occupies only 1 byte not 4 (you are mistaking it for an int array)
by the way you don't have any strings in your code
I don't recommend the code you have written for calculator, yet wanted to help you find the working code. Try following code that is based on your own code. Hope you'll see the differences and understand the reasons why the program was crashing in your case.
#include <Windows.h>
#include <stdio.h>
#include <stdbool.h>
bool checkNumber(int num)
{
return true;
}
int calculate(int a, int b) {
return a + b;
}
void calculatorPrompt() {
int a = 0;
int b = 0;
int sum = 0;
printf("Enter your first number: ");
scanf_s("%d", &a);
if (checkNumber(a)) {
}
printf("Enter your second number: ");
scanf_s("%d", &b);
if (checkNumber(b)) {
}
sum = calculate(a, b);
printf("Your answer is: %d", sum);
}
int main()
{
printf("Thanks for that\nDo you want a calculator?(y/n)");
char answer = 'n';
scanf_s("%c", &answer);
if (answer == 'y') {
calculatorPrompt();
}
else if (answer == 'n') {
printf("Okay bye!");
Sleep(100); //wait for 100 milliseconds
}
}
#include <windows.h>
#include <stdio.h>
#include <stdbool.h>
void calculatorPrompt(void);
int main(void){
printf("Thanks for that\nDo you want a calculator?(y/n)");
char answer = 'n';
scanf("%c", &answer);//scanf need address of store place
if(answer == 'y') {
calculatorPrompt();
} else if(answer == 'n') {
printf("Okay bye!\n");
Sleep(100); //wait for 100 milliseconds
}
return 0;
}
void checkNumber(void);
int calculate(int a, int b);
void calculatorPrompt() {
int a = 0;
int b = 0;
int sum = 0;
printf("Enter your first number: ");
if(scanf("%d", &a) != 1) {//\n : skip white spaces and wait input not spaces
checkNumber();//call when invalid input
} else {
printf("Enter your second number: ");
if(scanf("%d", &b) != 1) {
checkNumber();
} else {
sum = calculate(a, b);
printf("Your answer is: %d\n", sum);
}
}
}
void checkNumber(void){//output message and clear input.
fprintf(stderr, "invalid input!\n");
scanf("%*[^\n]%*c");//clear upto end of line.
}
int calculate(int a, int b) {
return a + b;
}
When you scan a character , you just need to use %c. If you are planning to continue with string you must use strcmp() for comparison not ==.
I am using Microsoft Visual Stusio 2013 Community Edition Update 4 to write a program in the C programming language (not C++). Whenever I try to build and run my program, partway through execution it tells me "Unhandled exception at 0x52873FD4 (msvcr120d.dll) in program.exe: 0xC0000005: Access violation writing location 0x00C40000." When I copy and paste the contents of the .c file into another IDE (code blocks) it compiles and runs without a problem. (Although I do have to change all the scanf_s statements in the code to scanf)
The source code from within the .c file of my program
#include <math.h>
#include <stdio.h>
#include <string.h>
#define PI 3.14159265358979323846;
double add();
double cos_d_r();
double div();
double mult();
void list();
int main()
{
//Declaration of variables
char oper[20];
double ans;
int loop = NULL;
//While loop allows for multiple executions without restarting program
while (!loop)
{
printf("\n\nEnter a mathematical operation.\n\nFor a list of options, enter 'list'\n\n");
scanf_s(" %s", oper);
//If statement to determine which operation to do
//Addition
if (strcmp(oper, "add") == 0 || strcmp(oper, "addition") == 0 || oper[0] == '+')
{
ans = add();
printf("The sum is %.2f\n", ans);
}
//Cosine
else if (strcmp(oper, "cos") == 0 || strcmp(oper, "cosine") == 0)
{
ans = cos_d_r();
printf("The cosine of the angle is %lf\n", ans);
}
//Division
else if (strcmp(oper, "divide") == 0 || strcmp(oper, "division") == 0 || oper[0] == '/')
{
ans = div();
printf("The quotient is %.2f\n", ans);
}
//List of possible operations
else if (strcmp(oper, "list") == 0)
{
list();
}
//Multiplication
else if (strcmp(oper, "multiply") == 0 || strcmp(oper, "multiplication" == 0) || oper[0] == '*')
{
ans = mult();
printf("The product is %.2f", ans);
}
}
return 0;
}
//Declaration of functions
//Addition
double add()
{
double ans;
double num_1;
double num_2;
puts("Enter the first number");
scanf_s(" %lf", &num_1);
puts("Enter the second number");
scanf_s(" %lf", &num_2);
ans = num_1 + num_2;
return ans;
}
//Cosine
/*Uses cos() function from math.h
this function adds option for degrees or radians*/
double cos_d_r()
{
char deg_rad;
double angle;
double ans;
int loop = NULL;
while (!loop)
{
puts("Degrees or radians? Enter 'd' or 'r'");
scanf_s(" %c", °_rad);
//Degrees
if (deg_rad == 'd')
{
puts("Enter an angle in degrees");
scanf_s(" %lf", &angle);
angle = angle / 180 * PI;
ans = cos(angle);
loop = 1;
return ans;
}
//Radians
else if (deg_rad == 'r')
{
puts("Enter an angle in radians");
scanf_s(" %lf", &angle);
ans = cos(angle);
loop = 1;
return ans;
}
//Else statement repeats loop if user enters text other than 'd' or 'r'
else
{
puts("ERROR. Enter either 'd' or 'r'");
}
}
}
//Division
double div()
{
double ans;
double num_1;
double num_2;
puts("Enter the dividend");
scanf_s(" %lf", &num_1);
puts("Enter the divisor");
scanf_s(" %lf", &num_2);
ans = num_1 / num_2;
return ans;
}
//Multiplication
double mult()
{
double ans;
double num_1;
double num_2;
puts("Enter the first number");
scanf_s(" %lf", &num_1);
puts("Enter the second number");
scanf_s(" %lf", &num_2);
ans = num_1 * num_2;
return ans;
}
//List of possible operations
void list()
{
printf("The possible operations are:\n\n");
printf("Operation\tDescription\tCommand");
printf("Addition\tAdds two numbers together\tAdd, Addition, +\n");
printf("Cosine\tFinds the cosine of the angle entered\tCos, Cosine");
printf("Division\tDivides the first number by the second\tDivide, Division, /");
printf("Multiplication\tMultiplies the two numbers\tMultiply, Multiplication, *");
}
You should read description of functions you use first! Take a look at scanf_s function description at MSDN. You programm crashes at first call of this function
scanf_s(" %s", oper);
The correct way to use it:
scanf_s("%s", oper, _countof(oper)); // or sizeof(oper), but only with char array
Also you should correct other calls of scanf_s in your code. (Or disable errors for scanf call with #define _CRT_SECURE_NO_WARNINGS before #include <stdio.h>)
I need to write a simple program in C that makes simple calculations of: +,-,*,/
Now, I am using Visual Studio Express 2013, and here is the code:
#include <stdio.h>
#include <stdlib.h>
int main(){
double a, b;
double sum = 0;
char o; //operator
printf("Enter operator\n");
scanf_s("%c", &o);
printf("Enter first operand\n");
scanf_s("%f", &a);
printf("Enter second operand\n");
scanf_s("%f", &b);
if (o == '+'){
sum = a + b;
printf("The result is", &sum);
}
if (o == '-'){
sum = a - b;
printf("The result is", sum);
}
if (o == '*'){
sum = a*b;
printf("The result is", sum);
}
if (o == '/'){
if (b == !0){
sum = a / b;
printf("The result is", sum);
}
else printf("Error");
}
getchar();
}
My output: Enter operator
+
Enter first operand
3.5
Enter second operand
5.4
And after I type the second number- the program exits, and nothing!
There are no compilation errors, and I have no idea what to do. Can someone help, please?
You're not using printf correctly. This is what you're using.
printf("The result is", &sum);
You're not specifying the type of output in the format string, and you're passing the address of the variable you want to print, not the value.
You should use:
printf("The result is %lf\n", sum);
%lf is specifying that you want to print a double, \n adds a newline, and you pass the value of the variable sum, not it's address.
Also, you should change if (b == !0){ to if (b != 0){. If you leave what you put, it's the equivalent to if (b == 1){, which probably isn't what you want.
EDIT Here is the code, with my modifications, which gives correct results. I'll indicate which lines I changed
#include <stdio.h>
#include <stdlib.h>
int main(){
double a, b;
double sum = 0;
char o; //operator
/* I had to use scanf, since I'm not using MS/Visual Studio, but GCC */
printf("Enter operator\n");
scanf("%c", &o);
printf("Enter first operand\n");
scanf("%lf", &a); /* changed %f to %lf */
printf("Enter second operand\n");
scanf("%lf", &b); /* changed %f to %lf */
/* I prefer to use if ... else if ..., this is personal preference */
if (o == '+'){
sum = a + b;
printf("The result is %lf\n", sum); /* Changed, see original post */
} else if (o == '-'){
sum = a - b;
printf("The result is %lf\n", sum); /* Changed, see original post */
} else if (o == '*'){
sum = a*b;
printf("The result is %lf\n", sum); /* Changed, see original post */
} else if (o == '/'){
if (b != 0){
sum = a / b;
printf("The result is %lf\n", sum); /* Changed, see original post */
}
else printf("Error");
}
getchar();
return 0;
}
You are using %f format to read doubles. You should use %lf:
scanf_s("%lf", &a);
The print methods actually don't print the result (format is incomplete). And, instead of the value, you are passing variable's address. It should be:
printf("The result is %e", sum);
You should also change if (b == !0) to if (b != 0)
Now it's working fine I made some changes to it
the problem was with ur "scanf_s" and "%f" go throw with it
#include<stdio.h>
#include<stdlib.h>
int main(){
double a, b;
double sum = 0;
char o; //operator
printf("Enter operator\n");
scanf("%c", &o);
printf("Enter first operand\n");
scanf("%d", &a);
printf("Enter second operand\n");
scanf("%d", &b);
if (o == '+'){
sum = a + b;
printf(" The result is %d", sum);
}
if (o == '-'){
sum = a - b;
printf("The result is %d", sum);
}
if (o == '*'){
sum = a*b;
printf("The result is %d", sum);
}
if (o == '/'){
if (b == !0){
sum = a / b;
printf("The result is %d", sum);
}
else printf("Error");
}
getchar();
}