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();
}
Related
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.
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 wrote a code that count how many zeros, odds and evens are in the numbers provided by the user.
How do I need to change this code, so that in result i have :
Numbers from user without odds (for example if user writes 1234 i need that program will write 24)
Numbers from user without zeros. (for example if user writes 1005 i need that program will write 15)
Thank you.
int sk,a=0,b=0,c=0;
printf ("Write number: ");
scanf("%d", &sk);
while (sk!=0){
if (sk%10==0){
a++;
}
else if (sk%2==0){
b++;
}
else {
c++;
}
sk=sk/10;
}
printf(" Zeros %d \n Evens %d \n Odss %d ",a , b, c);
This may help :)
int sk,a=0,b=0,c=0;
int cnt_a=1,cnt_b=1,cnt_c=1;
printf ("Write number : ");
scanf("%d", &sk);
while (sk != 0){
if (sk%10 != 0){
a = a + (sk%10 * cnt_a);
cnt_a *= 10;
}
if (sk%2==0){
b = b + (sk%10 * cnt_b);
cnt_b *= 10;
}
else {
c = c + (sk%10 * cnt_c);
cnt_c *= 10;
}
sk = sk/10;
}
printf(" Without Zeros : %d \n Only Evens : %d \n Only Odds : %d ", a , b, c);
Change your 'printf' function, like above this, and you will receive your missing variables.
int sk,a=0,b=0,c=0;
printf ("Write number: ");
scanf("%d", &sk);
while (sk != 0) {
if (sk%10 == 0){
a++;
}
else if (sk%2 == 0){
b++;
}
else {
c++;
}
sk = sk/10;
}
printf(" Zeros %d \n Evens %d \n Odss %d \n Without Zeros: %d \n Without Odds: %d \n",a , b, c, b+c, a+b);
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'm trying to making a rudimentary calculator that can perform a variety of arithmetic functions, starting with addition! Right now I've got the basic logic of it worked out, but I'm not sure exactly how to take two inputs and print it out!
#include <stdio.h>
int main()
{
char mychar;
int a;
int op1;
int op2;
printf("Welcome to Andrew Hu's calculator program!\n"); //Greeting
while(1)
{ printf("Enter a mathematical operation to perform:\n");
scanf("%c", &mychar);
if(mychar == '+') //Valid Operators
a = 1;
else
a = 0;
if(a == 0) //Operator Checker, error if invalid
printf("\nError, not a valid operator\n");
else if(a == 1){
printf("%c\n", &mychar),
printf("Enter OP1:\n"),
/* not sure what to put here to echo the character as a decimal*/
printf("Enter OP2:\n"),
/* not sure what to put here to echo the character as a decimal either*/
printf("Result of %d %c %d = %d\n", op1, mychar, op2, (op1 + op2) )
/* this last line I'm not too sure of. I'm trying to print out the expression
which is op1 + op2 = the sum of both. */
;
}
}
use scanf statement to take the inputs,just the same way you have taken mathematical operators.A switch case statement would be good to implement the calculator.
scanf(" %d",&op1);
Use the scanf function to read in a floating-point value like
double op1 = 0.0;
scanf("%lf", &op1);
The %lf denotes to read the entered value as a float-value.
As you enter the values on the command-line they will be displayed.
else if(a == 1){
printf("%c\n", mychar), // don't use & with printf as it will print the address of mychar
printf("Enter OP1:\n"),
double op1 = 0.0;
scanf("%lf", &op1);
printf("Enter OP2:\n"),
double op2 = 0.0;
scanf("%lf", &op2);
if(a == 1)
printf("Result of %lf + %lf = %lf\n", op1, op2, (op1 + op2) );
}