The calculator program was an assignment for my C introduction web class.
How would I better include this section: (currently included in every else if statement)
printf("\nSyötä ensimmäinen luku:");
scanf("%d", &ekaluku);
printf("Syötä toinen luku:");
scanf("%d", &tokaluku);
in the code without changing output?
Source code:
#include <stdio.h>
int laskesumma(int a, int b);
int laskeerotus(int a, int b);
int lasketulo(int a, int b);
int main(void)
{
int valinta, ekaluku, tokaluku;
do {
printf("1: kahden luvun summa\n2: kahden luvun erotus\n3: kahden luvun tulo\n<0: ohjelman lopetus\n\nValitse laskutoimitus:");
scanf("%d", &valinta);
if (valinta < 0)
{ printf("Ohjelma lopetetaan...\n\n"); }
else if (valinta == 1)
{
printf("\nSyötä ensimmäinen luku:");
scanf("%d", &ekaluku);
printf("Syötä toinen luku:");
scanf("%d", &tokaluku);
printf("%d + %d = %d\n\n", ekaluku, tokaluku, laskesumma(ekaluku,tokaluku));
}
else if (valinta == 2)
{
printf("\nSyötä ensimmäinen luku:");
scanf("%d", &ekaluku);
printf("Syötä toinen luku:");
scanf("%d", &tokaluku);
printf("%d - %d = %d\n\n", ekaluku, tokaluku, laskeerotus(ekaluku,tokaluku));
}
else if (valinta == 3)
{
printf("\nSyötä ensimmäinen luku:");
scanf("%d", &ekaluku);
printf("Syötä toinen luku:");
scanf("%d", &tokaluku);
printf("%d * %d = %d\n\n", ekaluku, tokaluku, lasketulo(ekaluku,tokaluku));
}
else
{ printf("Antamasi luku ei kelpaa.\n"); }
} while (valinta>0);
return 0;
}
//Addition
int laskesumma(int a, int b) {
int tulos;
tulos = a+b;
return tulos;
}
//Subtraction
int laskeerotus(int a, int b) {
int tulos;
tulos = a-b;
return tulos;
}
//Multiplication
int lasketulo(int a, int b) {
int tulos;
tulos = a*b;
return tulos;
}
Is there anything else I could fix for better readability or decreasing the size of the program?
One possibility is:
int ekaluku_tokaluku(int *ekaluku, int *tokaluku)
{
printf("\nSyötä ensimmäinen luku:");
if (scanf("%d", ekaluku) != 1)
return EOF;
printf("Syötä toinen luku:");
if (scanf("%d", tokaluku) != 1)
return EOF;
return 0;
}
Note that the variables are passed to the function as pointers, so there is no & in the scanf() calls. Some people might use a prefix such as p_ekaluku (or pEkaluku) on the names to indicate that they're a pointer.
You'd use it like this:
else if (valinta == 1)
{
if (ekaluku_tokaluku(&ekaluku, &tokaluku) != 0)
break;
printf("%d + %d = %d\n\n", ekaluku, tokaluku, laskesumma(ekaluku, tokaluku));
}
Returning 0 on success is a common pattern. It's always worth checking that your code handles EOF conditions. You could consider adding fflush(stdout); after the printf() and before the scanf() statements in the function.
Just use a function if you're repeating those lines of codes a lot and return the integer value.
int userInput() {
int ekaluku;
printf("\nSyötä ensimmäinen luku:");
scanf("%d", &ekaluku);
return ekaluki;
}
Whenever you repeat a code block somewhere in your program, you should always consider to put that code block into a function. That will make it much easier to maintain your code.
Besides that I'll suggest that you don't use scanf - it has many surprises. For instance try to give your program the input 1a
Instead use sscanf and fgets as they'll give you less surprises.
The function could look like:
int get_input(FILE *fp, int n)
{
int d = 0;
char line[LINESIZE];
if (n > 0)
{
printf("Input the %d. number\n", n);
}
if(!fgets(line, LINESIZE,fp))
{
printf("Error reading input\n");
return 0;
}
if (sscanf(line, "%d", &d) != 1)
{
printf("Error reading input\n");
return 0;
}
return d;
}
and it can be used like:
do
{
printf("1: kahden luvun summa\n2: kahden luvun erotus\n3: kahden luvun tulo\n<0: ohjelman lopetus\n\nValitse laskutoimitus:");
valinta = get_input(stdin, 0);
if (valinta < 0)
{
printf("Ohjelma lopetetaan...\n\n");
}
else if (valinta == 1)
{
ekaluku= get_input(stdin, 1);
tokaluku= get_input(stdin, 2);
printf("%d + %d = %d\n\n", ekaluku, tokaluku, laskesumma(ekaluku,tokaluku));
}
This can be a little bit shorter (number of lines):
int laskesumma(int a, int b) { return (a+b);} //Addition
int laskeerotus(int a, int b){ return (a-b);} //Subtraction
int lasketulo(int a, int b) { return (a*b);} //Multiplication
but lower readibility in case of needed more complicated functions...
reduce code like this
#include <stdio.h>
#define make_func(name, op)\
static inline int name(int a, int b){\
return a op b;\
}\
/**/
make_func(laskesumma , +) //Addition
make_func(laskeerotus, -) //Subtraction
make_func(lasketulo , *) //Multiplication
#define op(no) ( " +-*"[no] )
typedef int (*Func)(int,int);
#define func(no) ( (Func[]){ 0, laskesumma, laskeerotus, lasketulo}[no] )
enum { QUIT, ADD, SUB, MUL };
int main(void){
int valinta, ekaluku, tokaluku;
do {
printf("%d: kahden luvun summa\n"
"%d: kahden luvun erotus\n"
"%d: kahden luvun tulo\n"
"<%d: ohjelman lopetus\n\n"
"Valitse laskutoimitus:", ADD, SUB, MUL, QUIT);fflush(stdout);
scanf("%d", &valinta);
switch(valinta){
case ADD:
case SUB:
case MUL:
printf("\nSyota ensimmainen luku:");fflush(stdout);
scanf("%d", &ekaluku);
printf("Syota toinen luku:");fflush(stdout);
scanf("%d", &tokaluku);
printf("%d %c %d = %d\n\n", ekaluku, op(valinta), tokaluku, func(valinta)(ekaluku, tokaluku));
break;
default:
if(valinta < QUIT){
printf("Ohjelma lopetetaan...\n\n");
return 0;
}
printf("Antamasi luku ei kelpaa.\n");
}
} while (valinta > QUIT);
return 0;
}
Try to use switch case in your code
do
{
if(valinta<0)
printf("Ohjelma lopetetaan...\n\n");
switch(valinta)
{
case 1:
case 2:
case 3:
printf("\nSyötä ensimmäinen luku:");
scanf("%d", &ekaluku);
printf("Syötä toinen luku:");
scanf("%d", &tokaluku);
break;
default: printf("Antamasi luku ei kelpaa.\n");
}
}while(valinta>0);
Related
whenever I input the scanf in this code
scanf("%d\n",&t);
for(i,x=1;i,x<=t;i,x++){
scanf("%d %d %d", &a, &b, &c);
if(b+c>=a){
printf("Case #%d: yes\n",x);
}
else{
printf("Case #%d: no\n",x);
}
}
it always become scanf -> printf -> scanf -> printf
and when i do this code
scanf("%d\n",&t);
for(i=1;i<=t;i++){
scanf("%d %d %d", &a, &b, &c);
}
for(x=1;x<=t;x++){
if(b+c>=a){
printf("Case #%d: yes\n",x);
}
else{
printf("Case #%d: no\n",x);
}
}
it does not get the input from scanf. each a,b,c has different value.
i want it to input all the scanf first then printf the result. how?
To store the values for later, use an array.
#include <stdio.h>
#include <stdlib.h>
int main()
{
size_t t;
if (scanf("%lu", &t) != 1) {
fputs("Incorrect input.", stderr);
return -1;
}
// Allocate a 2-d array with size t x 3
int (*arr)[3] = malloc(sizeof(int[t][3]));
if (!arr) {
fputs("Could not allocate memory.", stderr);
return -1;
}
// To use letters instead of numbers for the indexes
enum {A, B, C};
for (int i = 0; i < t; i++) {
if (scanf("%d %d %d", &arr[i][A], &arr[i][B], &arr[i][C]) != 3) {
fputs("Incorrect input.", stderr);
free(arr);
return -1;
}
}
for (int i = 0; i < t; i++) {
printf("Case #%d: ", i + 1);
if (arr[i][B] + arr[i][C] >= arr[i][A]) {
puts("yes");
}
else{
puts("no");
}
}
free(arr);
return 0;
}
This code uses dynamic memory allocation. If you haven't learned that yet, here's a simplified version with a fixed-size array:
#include <stdio.h>
int main()
{
int arr[100][3];
int t;
if (scanf("%d", &t) != 1 || t <= 0 || t > 100) {
puts("Incorrect input.");
return -1;
}
for (int i = 0; i < t; i++) {
if (scanf("%d %d %d", &arr[i][0], &arr[i][1], &arr[i][2]) != 3) {
puts("Incorrect input.");
return -1;
}
}
for (int i = 0; i < t; i++) {
printf("Case #%d: ", i + 1);
if (arr[i][1] + arr[i][2] >= arr[i][0]) {
puts("yes");
}
else{
puts("no");
}
}
return 0;
}
Something like this should work if you want to scanf -> printf -> scanf -> printf for all iterations:
#include <stdio.h>
int main(void)
{
int a, b, c;
int num_iterations;
printf("Enter number of iterations: ");
scanf("%d",&num_iterations);
for(int i = 0; i < num_iterations; ++i)
{
printf("Enter a, b, c: ");
scanf("%d %d %d", &a, &b, &c);
if (b+c >= a) {
printf("Case #%d: yes\n", i+1);
}
else {
printf("Case #%d: no\n", i+1);
}
}
return 0;
}
Something like this should work if you want to do all scanf's bfore all printf's:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int num_iterations;
printf("Enter number of iterations: ");
scanf("%d",&num_iterations);
int *a = malloc(num_iterations * sizeof(int));
int *b = malloc(num_iterations * sizeof(int));
int *c = malloc(num_iterations * sizeof(int));
for(int i = 0; i < num_iterations; ++i)
{
printf("Enter a, b, c for iter %d: ", i);
scanf("%d %d %d", &a[i], &b[i], &c[i]);
}
for(int i = 0; i < num_iterations; ++i)
{
if (b[i]+c[i] >= a[i]) {
printf("Case #%d: yes\n", i+1);
}
else {
printf("Case #%d: no\n", i+1);
}
}
free(a);
free(b);
free(c);
return 0;
}
my code is look like this:
int main(){
int choice=(1,2,3);
printf("1- Finabocci sequence\n");
printf("2- Check valid date\n");
printf("3- Quit\n");
printf("Choose an operation: \n");
scanf("%d", &choice);
switch(choice){
case 1:
{
int t1 = 0, t2 = 1, nextTerm = 0, n;
printf("Enter a positive number: ");
scanf("%d", &n);
printf("Fibonacci Series: %d, %d, ", t1, t2);
nextTerm = t1 + t2;
while(nextTerm <= n)
{
printf("%d, ",nextTerm);
t1 = t2;
t2 = nextTerm;
nextTerm = t1 + t2;
}
break;
}
case 2:
{
int validDate(int d,int m,int y){
if (m<1||m>12) return 0;
else if (m==1||m==3||m==5||m==7||m==8||m==10||m==12){
if (d>=1&&d<=31) return 1;
else return 0;
}
else if (m==4||m==6||m==9||m==11) {
if (d>=1&&d<=30) return 1;
else return 0;
}
else if (m==2) {
if (y%400==0||(y%4==0&&y%100!=0)) {
if (d>=1&&d<=29) return 1;
else return 0;
}
else if (d>=1&&d<=28) return 1;
else return 0;
}
}
int main(int validDate(int d,int m,int y)) {
int d,m,y;
printf ("Input day: ");
scanf("%d",&d);
printf ("Input month: ");
scanf("%d",&m);
printf ("Input year: ");
scanf("%d",&y);
if(validDate(d,m,y)!=0) printf("valid date");
else printf("invalid date");
return 0;
}
break;
}
default: printf("exit?");
getchar();
}
return 0;
}
I'm not really know how the option2 is not running at all, like the 1st one and the 3rd are normal. How do i can fix this :D
For example: I'm running the Option2 code alone and its work, but when i put in the switch then its wont work at all
First thing is int main(int validDate(int d,int m,int y)) should correct like this int validDate(int d,int m,int y)
In your case these codes cannot be like this.
int choice=(1,2,3); - wrong
int choice= 0; - right
other thing is
nextTerm = t1 + t2;
output -:0,1,1,2,3 --> wrong
nextTerm = t2 + 1;
output -:0,1,2,3 --> right
Another thing is you have to put break; statement after every cases and default either when you compiling your code its compile every cases and default you have given
Final thing is follow good coding methods. It also helps you to identify your errors
here the corrected code
#include <stdio.h>
int main(){
int choice = 0;
printf("1- Finabocci sequence\n");
printf("2- Check valid date\n");
printf("3- Quit\n");
printf("Choose an operation: \n");
scanf("%d", &choice);
switch(choice)
{
case 1:
{
int t1 = 0, t2 = 1, nextTerm = 0, n;
printf("Enter a positive number: ");
scanf("%d", &n);
printf("Fibonacci Series: %d, %d, ", t1, t2);
nextTerm = t2 + 1;
while(nextTerm <= n)
{
printf("%d, ",nextTerm);
t1 = t2;
t2 = nextTerm;
nextTerm = t1 + t2;
}
break;
}
case 2:
{
int validDate(int d,int m,int y)
{
if (m<1||m>12)
return 0;
else if (m==1||m==3||m==5||m==7||m==8||m==10||m==12)
{
if (d>=1&&d<=31)
return 1;
else
return 0;
}
else if (m==4||m==6||m==9||m==11)
{
if (d>=1&&d<=30)
return 1;
else
return 0;
}
else if (m==2)
{
if (y%400==0||(y%4==0&&y%100!=0)) {
if (d>=1&&d<=29)
return 1;
else
return 0;
}
else if (d>=1&&d<=28)
return 1;
else
return 0;
}
}
int d,m,y;
printf ("Input day: ");
scanf("%d",&d);
printf ("Input month: ");
scanf("%d",&m);
printf ("Input year: ");
scanf("%d",&y);
if(validDate(d,m,y)!=0) printf("valid date\n");
else printf("invalid date \n");
break;
}
default: printf("exit?");
break;
getchar();
}
return 0;
}
You are calling main fuction on main fuction. I fix the code for u.
int main(){
int choice=(1,2,3);
printf("1- Finabocci sequence\n");
printf("2- Check valid date\n");
printf("3- Quit\n");
printf("Choose an operation: \n");
scanf("%d", &choice);
switch(choice){
case 1:
{
int t1 = 0, t2 = 1, nextTerm = 0, n;
printf("Enter a positive number: ");
scanf("%d", &n);
printf("Fibonacci Series: %d, %d, ", t1, t2);
nextTerm = t1 + t2;
while(nextTerm <= n)
{
printf("%d, ",nextTerm);
t1 = t2;
t2 = nextTerm;
nextTerm = t1 + t2;
}
break;
}
case 2:
{
int validDate(int d,int m,int y){
if (m<1||m>12) return 0;
else if (m==1||m==3||m==5||m==7||m==8||m==10||m==12){
if (d>=1&&d<=31) return 1;
else return 0;
}
else if (m==4||m==6||m==9||m==11) {
if (d>=1&&d<=30) return 1;
else return 0;
}
else if (m==2) {
if (y%400==0||(y%4==0&&y%100!=0)) {
if (d>=1&&d<=29) return 1;
else return 0;
}
else if (d>=1&&d<=28) return 1;
else return 0;
}
}
int d,m,y;
printf ("Input day: ");
scanf("%d",&d);
printf ("Input month: ");
scanf("%d",&m);
printf ("Input year: ");
scanf("%d",&y);
if(validDate(d,m,y)!=0) printf("valid date\n");
else printf("invalid date \n");
}
default: printf("exit?");
getchar();
}
return 0;
}
Basically this is a program to play with dice but i have a problem with srand. it gives an error stating "implicit conversion loses integer precision: 'time_t' (aka 'long') to 'unsigned int'"
whys that ?
Also i would like to know if there are any other ways to improve this code? currently i only know stdio.h i know there are some out there like iostream or something like that. is there a possible way to explain those to me also.
Here is the code.
i know crt secure no warning is to ignore some errors but i would still like to know why it the error pops up ?
#define _CRT_SECURE_NO_WARNINGS
#define MAX_CHIPS 400
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void display_details(void);
int throws_die(void);
int main() so on
{
int die1, die2, throw_sum;
int PointToMake;
int Games_Played = 0;
int Games_Won = 0;
int Games_Lost = 0;
int CurrentChips = MAX_CHIPS;
int BetChips;
char PlayerName[30];
char PlayAgain;
display_details();
srand(time(NULL));
printf("Would you like to play Test your luck [y|n]?\n");
scanf(" %c", &PlayAgain);
while ((PlayAgain == 'y') && (CurrentChips > 0))
{
if (Games_Played == 0)//shows how many games played which is obviously 0
{
printf("A new chellenger! What is your name?\n");
scanf(" %s", &PlayerName);
printf("Hi %s!\n", PlayerName);
}
Games_Played = Games_Played + 1;//each new game it will increase by 1
printf("Number of chips: %d\n", CurrentChips);
printf("Place your bet:\n ");
scanf("%d", &BetChips);
while ((BetChips < 0) || (BetChips > CurrentChips))
{
printf("uuh ....You can only bet the chips you have.. (0-%d)!\n", CurrentChips);
printf("Place your bet: \n");
scanf("%d", &BetChips);
}
die1 = throws_die();
die2 = throws_die();
throw_sum = die1 + die2;
printf("You Got: %d + %d = %d\n", die1, die2, throw_sum);
if ((throw_sum == 7) || (throw_sum == 12))
{
//+1 to games won
Games_Won = Games_Won + 1;
//adding to bet balance
CurrentChips = CurrentChips + BetChips;
printf("XXXXX Winner! d(^_^) XXXXX\n");
}
else if ((throw_sum == 2) || (throw_sum == 3) || (throw_sum == 10))
{
Games_Lost = Games_Lost + 1;
CurrentChips = CurrentChips - BetChips;
printf("XXXXX Loser! :( XXXXX\n");
}
else
{
PointToMake = throw_sum;
printf("Points to make is: %d\n", PointToMake);
die1 = throws_die();
die2 = throws_die();
throw_sum = die1 + die2;
printf(" |--->> Spinned: %d + %d = %d\n", die1, die2, throw_sum);
while (throw_sum != PointToMake && throw_sum != 7)
{
die1 = throws_die();
die2 = throws_die();
throw_sum = die1 + die2;
printf(" |--->> Spinned: %d + %d = %d\n", die1, die2, throw_sum);
}
if (throw_sum == PointToMake)
{
printf("XXXXX Winner! (x2 the bet) XXXXX\n");
//x2 added to balance
CurrentChips = CurrentChips + 2 * BetChips;
Games_Won = Games_Won + 1;
}
else
{
Games_Lost = Games_Lost + 1;
CurrentChips = CurrentChips - BetChips;
printf("XXXXX Loser!:( XXXXX\n");
}
}
if (CurrentChips > 0)
{
printf("You now have %d chips.\n", CurrentChips);
printf("============================\n\n");
printf("Play Again %s [y|n]? ", PlayerName);
scanf(" %c", &PlayAgain);
printf("============================\n");
}
else
{
printf("you're out of chips.\n");
printf("XXXXX GG TRY AGAIN NEXT TIME XXXXX\n");
}
}
if (Games_Played == 0)
{
printf("Oh well.... better luck next time!\n");
}
else if (Games_Played == 1)
{
printf("%s played %d game and is cashing out with %d chips!\n", PlayerName, Games_Played, CurrentChips);
printf(" |---> Games won: %d\n", Games_Won);
printf(" |---> Games lost: %d\n", Games_Lost);
printf("Thanks for playing, come again to test that luck of yours %s.\n", PlayerName);
}
else
{
printf("%s played %d games and is cashing out with %d chips!\n", PlayerName, Games_Played, CurrentChips);
printf(" |---> Games won: %d\n", Games_Won);
printf(" |---> Games lost: %d\n", Games_Lost);
printf("\nThanks for playing, come again to test that luck of yours %s!\n", PlayerName);
}
return 0;
}
void display_details(void)
{
printf("File :.... assignment.c\n");
printf("Author :.... \n");
printf("Stud ID :.... \n");
printf("Email ID :.... \n");
printf("This is my own work as defined by the \n");
printf("University's Academic Misconduct Policy.\n");
}
int throws_die(void)
{
return 1 + rand() % 6;
srand is defined more or less like this:
void srand(unsigned int seed);
time is defined more or less like this:
__int64 time(__int64 *t);
Thus you pass an __int64 (64 bits) into an unsigned int (32 bits) parameter, which is not possible without potential trunctation. That's what the warning message is telling you.
I am suppoused not to use globals just functions. I don't know where to have int measurements[LENGTH], x, i; to work as it does. I also need a function to calculate de number of measurements(nrOfMeasurements) that user typed in in getMeasurements. for example if they typed in 4 instead f 10. This is needed for ex. to calculate the average.
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <limits.h>
#define LENGTH 10
const char *IntroMsg = "\n\t Hello To TEST THE PRGRAM!\n",
*MenuMsg = "\n\t Menu \n\t v (View) \n\t e (Enter) \n\t c (Compute) \n\t r (Reset) \n\t q (Quit) \n\n";
int measurements[LENGTH],//not here
x, i;//not here
void getMeasurements(){
for(x=0; x<LENGTH; x++){
printf("Enter number #%d: ", x+1);
scanf("%d", &measurements[x]);
if(measurements[x]==0){
break;
}
}
return;
}
void getView(){
printf("\t\n");
printf("Your measurements:\n");
if(x>0){
for (i = 0; i < x; i++){
printf("\b %d ", measurements[i]);
}
}
else if(x==0){
printf(" [NO MEASUREMENTS]");
}
printf("\n");
}
void getCompute(){
int min = INT_MAX;
int max = INT_MIN;
int calculus;
float sum;
for(x=0; x<LENGTH; x++){
if (measurements[x]<min) min=measurements[x];
if (measurements[x]>max) max=measurements[x];
sum=sum+measurements[x];
calculus= measurements[x] - (sum/LENGTH);
printf("[%d]", calculus);
}
printf("\nMax number: %d", max);
printf("\nMin number: %d", min);
printf("\nAverage: %.2f", sum/LENGTH);
printf("\n\n");
}
int main(){
while(1){
char choice;
puts (MenuMsg);
scanf(" %c", &choice);
if(choice=='e')
getMeasurements();
else if(choice=='v'){
getView();
}
else if(choice=='c'){
getCompute();
}
else if(choice=='q'){
break;
}
}
return 0;
}
You can do something like this:
#include <stdio.h>
#define MAX_LENGTH 10
const char *IntroMsg = "\n\t Hello To TEST THE PROGRAM!\n";
const char *MenuMsg = "\n\t Menu \n"
"\t v (View)\n"
"\t e (Enter)\n"
"\t c (Compute)\n"
"\t r (Reset)\n"
"\t q (Quit)\n\n";
int getMeasurements(int *measurements, int length) {
int i;
for (i = 0; i < length; i++) {
printf("Enter number #%d: ", i+1);
scanf("%d", &measurements[i]);
if(measurements[i] == 0) {
break;
}
}
return i;
}
void getView(const int *measurements, int length){
int i;
printf("\t\nYour measurements:\n");
if (length == 0) {
printf(" [NO MEASUREMENTS]\n");
return;
}
for (i = 0; i < length; i++) {
printf("\b %d ", measurements[i]);
}
printf("\n");
}
void getCompute(const int *measurements, int length) {
int min, max, calculus, i;
float sum = 0;
if (length == 0) {
printf(" [NO MEASUREMENTS]\n");
return;
}
min = max = measurements[0];
for (i = 0; i < length; i++){
if (measurements[i] < min) min = measurements[i];
if (measurements[i] > max) max = measurements[i];
sum += measurements[i];
calculus = measurements[i] - (sum / length);
printf("[%d]", calculus);
}
printf("\nMax number: %d", max);
printf("\nMin number: %d", min);
printf("\nAverage: %.2f", sum / length);
printf("\n\n");
}
int main() {
int measurements[MAX_LENGTH];
int measurements_count = 0;
int run = 1;
while (run) {
char choice;
puts(MenuMsg);
scanf(" %c", &choice);
switch (choice) {
case 'e':
measurements_count = getMeasurements(measurements, MAX_LENGTH);
break;
case 'v':
getView(measurements, measurements_count);
break;
case 'c':
getCompute(measurements, measurements_count);
break;
case 'q':
run = 0;
break;
default:
printf("Wrong input\n");
break;
}
}
return 0;
}
I want to make a simple C calculator only with "IF" and "IF ELSE" conditions and it don't let me choose an operator ("+, -, * or /"), just appear my last if condition.
#include <stdio.h>
int main(){
printf("\tCalculadora\n\n");
int num1, num2, total;
char oper;
printf("Introduza o primeiro numero: \n");
scanf("%d", &num1);
printf("Introduza o segundo numero: \n");
scanf("%d", &num2);
printf("Escolha a operacao que quer realizar!\n\n");
scanf("%c", &oper);
if(oper == '+'){
printf("O resultado e: %d", num1+num2);
}
else if(oper == '-'){
printf("O resultado e: %d", num1-num2);
}
else if(oper == '*'){
printf("O resultado e: %d", num1*num2);
}
else{
printf("O resultado e: %d", num1/num2);
}
getchar();
getchar();
}
I avoid scanf() and its cousins. Here is a version of your calculator that uses fgets() for the input. It also uses double for the operands.
#include <stdio.h>
#include <stdlib.h>
#define ISIZE 100 // arbitrarily large
int main(){
double num1, num2;
int oper;
char inp[ISIZE+1] = "";
printf("\tCalculadora\n\n");
printf("Introduza o primeiro numero: "); // 1st operand
fgets (inp, ISIZE, stdin);
num1 = atof (inp);
printf("Introduza o segundo numero: "); // 2nd operand
fgets (inp, ISIZE, stdin);
num2 = atof (inp);
printf("Escolha a operacao que quer realizar! "); // operator
fgets (inp, ISIZE, stdin);
oper = inp[0];
printf ("O resultado e: %f %c %f = ", num1, oper, num2);
switch (oper) {
case '+': printf("%f\n", num1+num2); break;
case '-': printf("%f\n", num1-num2); break;
case '*': printf("%f\n", num1*num2); break;
case '/': if (num2!=0) printf("%f\n", num1/num2);
else printf ("Divisão por zero!\n");
break;
default: printf("Eu não sei o que operador\n");
}
return 0;
}
This
scanf("%c", &oper);
should change to
scanf(" %c", &oper);
so you let scanf() ignore the '\n' left by previous scanf()s.
I was also trying to apply my knowladage of C in a simple calculator and came across you question. In order to respect your if...else request I've come up with this solution. I hope this helps.
#include <stdio.h>
void sayHello( ) {
printf("Hello\n"); }
// to say hello to the user
int add( int num1, int num2) {
num1 = num1 + num2;
return num1;
}
int minus( int num1, int num2) {
num1 = num1 - num2;
return num1;
}
int times( int num1, int num2) {
num1 = num1 * num2;
return num1;
}
int divide( int num1, int num2) {
num1 = num1 / num2;
return num1;
}
// This is to declare the calculations
void flush_input(){
int ch;
while ((ch = getchar()) != '\n' && ch != EOF); }
// This is to flush the scanf values
// Kudos to Huw Collingbourne, Udemy Teacher
int main(int argc, char **argv) {
char c;
char f;
int n1;
int n2;
int total;
// n1 = ' ';
// n2 = ' ';
sayHello();
do {
c = ' ';
printf("Insert the type of Calculation you want to make:\n");
printf("A(d)dition, Subs(t)raction, Mu(l)tiplication, Di(v)ision: ");
c = getchar();
if(c == 'd') {
printf("\nInsert the first number:");
scanf("%d", &n1);
printf("Insert the second number:");
scanf("%d", &n2);
total = add( n1, n2 );
printf("%d plus %d equals to %d\n", n1, n2, total );
flush_input(); } else {
if( c == 't') {
printf("insert the base number:");
scanf("%d", &n1);
printf("Insert the subtracting number:");
scanf("%d", &n2);
total = minus( n1, n2 );
printf("The difference between %d and %d is %d\n", n1, n2, total );
flush_input(); } else {
if( c == 'l') {
printf("insert the first number:");
scanf("%d", &n1);
printf("Insert second number:");
scanf("%d", &n2);
total = times( n1, n2 );
printf("%d times %d equals %d\n", n1, n2, total );
flush_input(); } else {
if( c == 'v') {
printf("insert the first number:");
scanf("%d", &n1);
printf("Insert second number:");
scanf("%d", &n2);
total = divide( n1, n2 );
printf("%d divided by %d equals %d\n", n1, n2, total );
flush_input();
} else {
printf("I couln't understand the instruction\n Reseting program\n");
}
}
}
}
f = ' ';
printf("\nDo you wish to make another calculation?\n");
printf("Choose (y)es or (n)ot: ");
f = getchar();
// scanf("%c", &c);
getchar();
} while( f != 'n' );
printf("\nThat's all folks!\n");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
//declaration of function
float cal (float a, float b, char o);
int main(int argc, char *argv[])
{
// declaration of variable
float num1,num2;
int inum1,inum2;
char o;
//initialization of variable
num1=0;
num2=0;
//input
printf("Enter 1st number\n");
scanf("%f",&num1);
//input
printf("operator\n");
scanf(" %c", &o);
//input
printf("Enter 2nd number\n");
scanf(" %f", &num2);
inum1=num1;
inum2=num2;
if(cal(num1,num2,o)==0)
{
printf("Math Error");
}
if(cal(num1,num2,o)==1)
{
printf("%d",inum1%inum2);
}
else
printf("%.3f\n",cal(num1,num2,o));
return 0;
}
//definening function
float cal (float a, float b, char o)
{
if (o=='+')
return a+b;
if (o=='-')
return a-b;
if (o=='*')
return a*b;
if (o=='%')
return 1;
if (o=='/')
if (b!=0)
return a/b;
if (b==0)
return 0;
}