selection and iteration - c++

I am trying to write a c++ program where you can choose which operation you want to make and then choose the quantity of numbers to calculate the result. And I want to use a getchar function, but I cannot figure it out.
How do you even make int so that it behaves like a variable?
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
/*char a_char;
a_char=getchar();
cout<<a_char;*/
int opcode;
int a, b;
int result;
printf("Program for Addition, Subtraction, Multiplication and Division\n");
printf("Enter Your Choice: 1 - Add, 2 - Sub, 3 - Mul, 4 - Div: ");
scanf("%d", &opcode);
printf("Enter First Number:");
scanf("%d", &a);
printf("Enter Second Number:");
scanf("%d", &b);
switch(opcode)
{
case 1:
result = a + b;
printf("%d + %d = %d", a, b, result);
break;
case 2:
result = a - b;
printf("%d - %d = %d", a, b, result);
break;
case 3:
result = a * b;
printf("%d * %d = %d", a, b, result);
break;
case 4:
result = a / b;
printf("%d / %d = %d\n%d %% %d = %d", a, b, result, a, b, a % b);
break;
}
}

Assuming, that you want to input the operation code via getchar, it would look something like this:
opcode = getchar();
and then in your switch you encase the values in singular quotes:
case '1':
....
case '2':
.... and so on

You can use the following code to achieve what you exactly need.
You can replace the following line,
scanf("%d", &opcode);
as
opcode=getchar();
opcode = opcode-'0';
Since getchar will give you ASCII Code. so you need to convert to integer value so you need to subtract '0'.
It is logic: '0' is 48 :)

Related

Fill missing user input with zeros

I have a function that parses user input into the correct overloaded function. My "parseUserInput" function determines if the user entered a character, a floating-point, or an integer array. Then it calls the overloaded function to ultimately determine the average grade. The problem I am facing is, when I enter an integer array, I want to ensure if the user doesn't enter 5 integers, that the rest get filled in with zeros.
Example: "55 66 98 32 87" would work.
Example: "55 66" would not work... I want the compiler to understand the missing variables should be auto-filled to zero, such as .... " 55 66 0 0 0".
Any thoughts on how I can do this?
void parseUserInput(char *userInput)
{
int array[ASSGN_MARK];
/* other code ... */
else if (sscanf(userInput, "%i %i %i %i %i", &array[0], &array[1], &array[2], &array[3], &array[4]))
{
printf(">> This input should be directed to the << assessGrade(int[]) >> function ...\n");
assessGrade(array);
}
/* other code...*/
}
//Overloaded Function
void assessGrade(int array[ASSGN_MARK])
{
int total = 0;
int sum = 0;
sum = array[0] + array[1] + array[2] + array[3] + array[4];
total = sum / ASSGN_MARK;
//being type-casted to a double, as I'm calling the next overloaded function
//and that overloaded function will display if the student passed or failed
assessGrade((double)total);
}
As this is a C++ question, I recommend you do it the C++ way, and use std::vector. You can initialize the elements to zero like this:
std::vector < int > array(5, 0);
You'll also need to pass a reference, create a class to put both functions in, or make it global, because the way you have it right now, the other function can't see array.
I've figured out how to make these two functions work..
First, I've changed my function prototype to use default parameters. Therefore, if the user doesn't enter a number the number gets defaulted to 0.
void parseUserInput(char *userInput)
{
/* other code... */
else if (sscanf(userInput, "%i %i %i %i %i", &a, &b, &c, &d, &e))
{
printf(">> This input should be directed to the << assessGrade(int[]) >> function ...\n");
assessGrade(a, b, c, d, e);
}
/* other code... */
}
void assessGrade(int a, int b, int c, int d, int e)
{
int total = 0;
int sum = 0;
sum = a + b + c + d + e;
total = sum / 5;
assessGrade((double)total);
}

c++ using user input data for multiple functions

Hi i am looking to write a program for a arbitrary triangle.
Whilst i have completed the first part of my task which is to find if the triangle is either true or false. i want to be able to use the data inputted by the user to calculate the perimeter then eventually the area of the triangle.
But when the perimeter is calculated it is rather huge number.
This is my code so far.#include "stdafx.h"
#include "math.h"
enter code here
// ConsoleApplication6.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "math.h"
/* enter three variables a, b ,c to create a triangle*/
int main()
{
double a; /*insert dimensions of side a*/
double b; /*insert dimensions of side b*/
double c; /*insert dimensions of side c*/
double p; /*variable for the perimeter of a triangle*/
double s; /*variable for the area of a triangle*/
/* Get the user to enter the dimensions of a*/
printf_s("enter the dimensions of a: ");
scanf_s("%d", &a);
/* Get the user to enter the dimensions of b*/
printf_s("enter the dimensions of b: ");
scanf_s("%d", &b);
/* Get the user to enter the dimensions of c*/
printf_s("enter the dimensions of c: ");
scanf_s("%d", &c);
/* Conditions of a triangle*/
if ("a + b > c && a + c > b && b + c > a")
printf_s("True\n"); /* Display True if able to make a triangle*/
else printf_s("False\n"); /* Display false if unable to make a triangle*/
double p = a + b + c;
/*Scan user input data a, b, c*/
scanf_s("%d", &a, "%d", &b, "%d", &c);
/*output total perimeter*/
printf_s("The perimeter of the triangle is: ""%d, p");
return 0;
}
The problems is that all %d should be replaced by %lf in order to match the type double.
And also remove the line scanf_s("%d", &a, "%d", &b, "%d", &c);, once you scan once, you cannot scan again to get the same value.

Floating Point Exception Error

This program compiles fine, but it returns a message "Floating Point Exception" when I run it. I've looked at other threads and the problem appears to be dividing by 0, but I have looked over the program and there's no division by zero in my entire program. I even used the absolute value function in case.
By the way, the program is meant to reduce fractions.
Example input: 6 12, representing the fraction 6/12
Expected output: 1/2
#include <stdio.h>
/*declaring variables*/
int num1, num2, num1b, num2b, gcd, x;
int higher, lower, higher_2, lower_2;
/*declaring functions*/
int find_gcd(int num1, int num2);
void reduce(int numerator, int denominator, int *reduced_numerator, int *reduced_denominator);
int main(void)
{
do
{
printf("enter 2 numbers: ");
scanf("%d %d", &num1, &num2);
reduce(higher, lower, &higher_2, &lower_2);
printf("enter 0 to end program and any number continue: \n");
scanf("%d", &x);
} while(x != 0);
return 0;
}
void reduce(int numerator, int denominator, int *reduced_numerator, int *reduced_denominator)
{
num1=numerator;
num2=denominator;
gcd =find_gcd(numerator, denominator);
*reduced_numerator = (numerator/abs(gcd));
*reduced_denominator = (denominator/abs(gcd));
printf("The GCD is %d/%d\n", *reduced_numerator, *reduced_denominator);
}
int find_gcd(int m, int n)
{
while (n != 0) {
int remainder = m % n;
m = n;
n = remainder;
}
return m;
}
Your main problem is that you are not passing your input values num1 and num2 into your reduce() function. Instead you are passing in the global variables higher and lower. You didn't assign any values to them, but global variables are always initialized to 0 by default. Therfore, you run into the exception, because in reduce() you divide 0 by 0. You can verify that with a debugger.
If I change your main() as follows, then your code is at least working for your test case with 6 and 12 as input:
int main(void)
{
do
{
printf("enter 2 numbers: ");
scanf("%d %d", &num1, &num2);
reduce(num1, num2, &higher_2, &lower_2);
printf("enter 0 to end program and any number continue: \n");
scanf("%d", &x);
} while(x != 0);
return 0;
}
Output:
enter 2 numbers: 6
12
The GCD is 1/2
enter 0 to end program and any number continue:
As indicated in the comments you should also get rid of global and spurious variables. Therefore, you should first delete the following lines in your code:
/*declaring variables*/
int num1, num2, num1b, num2b, gcd, x;
int higher, lower, higher_2, lower_2;
Then let your main() function start the following way:
int main(void)
{
int num1, num2, higher_2, lower_2, x;
...
}
And your reduce() function should read like this:
void reduce(int numerator, int denominator, int *reduced_numerator, int *reduced_denominator)
{
int gcd = find_gcd(numerator, denominator);
*reduced_numerator = (numerator/abs(gcd));
*reduced_denominator = (denominator/abs(gcd));
printf("The GCD is %d/%d\n", *reduced_numerator, *reduced_denominator);
}
So far, you don't use your variables higher_2 and lower_2 in the main() function, but I guess you plan to do so. If not, you can also get rid of them together with parameters 3 and 4 of your reduce() function.
There is another issue with the code you provided (thanks to #user3629249 for pointing it out): You are missing an include for the abs() function. So you need to add the line #include <stdlib.h> at the beginning of your code (include <math.h> will also so the trick, as well as include <Windows.h> on Windows).

C Program Skipping if Statements Even When Conditions Are Met

Trying to solve this question I have for HW but I'm stuck with one little problem. I have a series of if statements but the program just skips every if statement even when the condition is met. Ex: User wants to execute 5 - 2, instead of going to the second if statement to check for when the user entered the minus, the program just skips every single if statement.
The question is:
Consider a C program that reads two real numbers from the keyboard
followed by a character where the character can be one of the
operators +, -, *, /, or % providing the addition, subtraction,
multiplication, division, or remainder respectively. Then the result
is displayed on the screen. For example, if the user types:
2.0 3.0 % then your code will display: 2 % 3 = 2 Note: In the above example the inputs are real numbers but the remainder only performs an
integer operation. Hence, the two real numbers must be type cast to
allow computation by remainder. In the case where an invalid operator
is entered (e.g. $) then an error message is printed to the standard
output, e.g. Invalid entry!
My code is:
#include <stdio.h>
int main(void){
double num1, num2, plus, minus, divide, mult, op;
printf("Enter two numbers and an operation you would like to perform on those number: \n");
scanf("%lf %lf %lf", &num1, &num2, &op);
if(op=='+')
{
plus=(num1 + num2);
printf("%lf + %lf = %lf", num1, num2, plus);
}
else if(op=='-')
{
minus=num1-num2;
printf("%lf - %lf = %lf", num1, num2, minus);
}
else if(op=='/')
{
divide=num1/num2;
printf("%lf / %lf = %lf", num1, num2, divide);
}
else if(op=='%')
{
int num1, num2, remain;
remain= (num1%num2);
printf("%d %% %d = %d", num1, num2, remain);
}
else
{
printf("Invalid entry!");
}
return 0;
}
Would really appreciate some help on this, have been struggling for a while on such a small error.
Try putting the line
printf("op=%lf\n",op);
right below your scanf statement to see what value op has for different operations. That solves the mystery of why the if statements were being skipped.
Then, as #l-l suggests, try declaring op as char op;.
#include <stdio.h>
int main(void)
{
double num1, num2, plus, minus, divide, mult, op;
char operation;
printf("Enter first number");
scanf("%lf", &num1);
printf("Enter second number");
scanf("%lf", &num2);
printf("Enter operation");
scanf(" %c", &operation);
if(operation=='+')
{
plus=(num1 + num2);
printf("%lf + %lf = %lf", num1, num2, plus);
}
if(operation=='-')
{
plus=(num1 - num2);
printf("%lf - %lf = %lf", num1, num2, plus);
}
if(operation=='/')
{
plus=(num1 / num2);
printf("%lf / %lf = %lf", num1, num2, plus);
}
if(operation=='*')
{
plus=(num1 * num2);
printf("%lf * %lf = %lf", num1, num2, plus);
}
return 0;
}
Try this. The code compiled and working fine.

creat random number in double format, eclipse stop working

generate random number 0-1, when I type the input number less than 4, the code works fine. However when the input number above 4, the eclipse stop working. what's wrong with my code
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
double ran(double x0, double x1){
return x0+(x1-x0)*rand()/((double)RAND_MAX);
}
int main(void) {
int a,i;
double *b;
printf("input the size\n");
scanf("%d", &a);
b=(double*)malloc(sizeof(int)*a);
srand((unsigned)time(NULL));
for(i=0;i<a;i++)
{
b[i]=ran(0,1);
printf("\n %f", b[i]);
}
free (b);
return 1;
}
A double is bigger than an integer. A double is eight bytes, while an integer is 4 bytes.
You should replace
b = (double*)malloc(sizeof(int)*a);
with
b = (double*)malloc(sizeof(double)*a);
or even better (thaks to Lưu Vĩnh Phúc)
b = malloc(a * sizeof b[0]);