function and pointers - c

I'm trying to write a program that would convert celcius to fahrenheit and visa-versa. My program is compiling, but it gives me wrong results. I'm been trying to change it by changing pointers, but it wouldnt work. Can anyone please point out to me what is my problem? It seems to me it's in declarations and pointers, but i'm not sure.Thanks!
#include<stdio.h>
float f2c(float f);
float c2f(float c);
int main(void)
{
float cel;
float celcius;
float fahren;
float fah;
char ch;
float number;
scanf("%c %f", &ch, &number);
if(&ch == "-f"){
f2c(number);
celcius=f2c(number);
printf("%f", celcius);
}
else{
c2f(number);
fahren = c2f(number);
printf("%f", fahren);
}
return 0;
}
float f2c(float f)
{
float cel = (f - 32) * 5/9;
return cel;
}
float c2f(float c)
{
float fah = (9 * c/5 + 32);
return fah;
}

if(&ch == "-f") this is the problem.
It should be :
if(ch == 'f')

In addition to the other answers:
You are doing needless calls to the conversion functions and throwing away the results, just before doing the same calls again but with proper handling of the return value:
if(&ch == "-f"){
f2c(number); /* This line does absolutely nothing! */
celcius=f2c(number);
printf("%f", celcius);
}

You are comparing char with a C-string "-f". Use strcmp to compare C-strings.
You may also have declare ch as char array to more than one character which you need here. Because, you can't store "-f" in a single char as you do now.
With the changes:
#include<stdio.h>
float f2c(float f);
float c2f(float c);
int main(void)
{
float cel;
float celcius;
float fahren;
float fah;
char ch[25];
float number;
scanf("%s %f", ch, &number);
if(strcmp(ch,"-f")==0){
f2c(number);
celcius=f2c(number);
printf("%f", celcius);
}
else{
c2f(number);
fahren = c2f(number);
printf("%f", fahren);
}
return 0;
}
float f2c(float f)
{
float cel = (f - 32) * 5/9.0;
return cel;
}
float c2f(float c)
{
float fah = (9 * c/5.0 + 32);
return fah;
}
This is essentially your code, but modified it to read the input as C-string.

Use floating-point arithmetic, not integer arithmetic, because in integer arithmetic, 5/9 is 0. So you could make this change to your code (though float parameters are unusual):
float f2c(float f)
{
return (f - 32.0) * 5.0/9.0;
}
float c2f(float c)
{
return 9.0 * c/5.0 + 32.0;
}
Also as one of the other answers states, the condition (&ch == "-f") is never true.
Here is a complete working example, with error checking.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <errno.h>
#include <assert.h>
static double f2c(double f)
{
return (f - 32.0) * 5.0/9.0;
}
static double c2f(double c)
{
return 9.0 * c/5.0 + 32.0;
}
int main (int argc, char *argv[])
{
int i;
const char *label_f = "Fahrenheit";
const char *label_c = "Celcius";
const char *from, *to;
double (*conversion)(double);
from = label_c;
to = label_f;
conversion = c2f;
for (i=1; i<argc; ++i)
{
if (0 == strcmp(argv[i], "-f"))
{
from = label_f;
to = label_c;
conversion = f2c;
}
else if (0 == strcmp(argv[i], "-c"))
{
from = label_c;
to = label_f;
conversion = c2f;
}
else
{
char *suffix = NULL;
double temp_in;
errno = 0;
temp_in = strtod(argv[i], &suffix);
if (ERANGE == errno)
{
if (HUGE_VAL == temp_in)
{
fprintf(stderr, "%s is too big", argv[i]);
return 1;
}
else
{
assert(-HUGE_VAL == temp_in);
fprintf(stderr, "%s is too small", argv[i]);
return 1;
}
}
else if (errno != 0 && (suffix == argv[i]))
{
/* no conversion was performed. */
fprintf(stderr, "%s is not a number", argv[i]);
return 1;
}
else if (*suffix)
{
fprintf(stderr, "Expected a number but saw '%s'\n", argv[i]);
return 1;
}
else
{
const double temp_out = (*conversion)(temp_in);
printf("%f %s is %f %s.\n", temp_in, from, temp_out, to);
}
}
}
return 0;
}

Related

C sscanf change other value [duplicate]

This question already has answers here:
Input too big for array
(4 answers)
Closed 2 years ago.
When I use sscanf, I found some other variable is changed as well but I don't know why.
My code is:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int add(int a, int b) {
return a + b;
}
int sub(int a, int b) {
return a - b;
}
int mul(int a, int b) {
return a * b;
}
int d(int a, int b) {
return a / b;
}
void manipulate(int* result, int x, int y, int op(int, int)) {
printf("%p\n", result);
*result = op(x, y);
}
int main() {
char line[20];
FILE* f = fopen("sample.txt", "r");
int result = 0;
while (fgets(line, 15, f) != NULL) {
char oper[3];
char valA[3];
char valB[3];
sscanf(&line[0], "%s %s %s", oper, valA, valB);
int x;
int y;
printf("%d\n", result);
if (valA[0] == '%') {
x = result;
y = atoi(valB);
} else if (valB[0] == '%') {
x = atoi(valA);
y = result;
} else {
x = atoi(valA);
y = atoi(valB);
}
printf("%d %d\n", x, y);
if (strcmp(oper, "ADD") == 0) {
manipulate(&result, x, y, &add);
} else if (strcmp(oper, "SUB") == 0) {
manipulate(&result, x, y, &sub);
} else if (strcmp(oper, "MUL") == 0) {
manipulate(&result, x, y, &mul);
} else if (strcmp(oper, "DIV") == 0) {
manipulate(&result, x, y, &d);
}
}
}
I used the debugger to track the value of the variable named result. In the first loop, the result becomes the value I want, but when it entre the second loop and finish the line sscanf, the result becomes 0 again. Could anyone tell me why? Thank you so much :)
Your char arrays are too small, because you didn't account for null terminators. The string ADD requires 4 characters ('A', 'D', 'D', and '\0'), but you're storing it in char oper[3], and writing past the end is Undefined Behavior. In this case, that happens to mean that the '\0' gets stored on top of result, setting it to 0.

C outputting variable positions (pointers) instead of actual values [duplicate]

This question already has answers here:
How to convert a string to integer in C?
(13 answers)
Closed 6 years ago.
I was working on a class project and I wanted to do a little bit extra and make validation on my data. The problem seems to happen at num1 = num1Input (and num2 = num2Input) where it is getting the location (I assume) instead of the actual input value
int main(void) {
//variables
char num1input[10];
char num2input[10];
int length, i;
int num1 = 0;
int num2 = 0;
int countErrors1 = 0;
int countErrors2 = 0;
bool correct1 = false;
bool correct2 = false;
//--end of variable declarations--//
do {
printf("Please enter a number: ");
scanf("%s", num1input);
length = strlen(num1input);
for (i = 0; i < length; i++) {
if (!isdigit(num1input[i])) {
countErrors1++;
}
}
if (countErrors1 > 0) {
printf("Input is not a number \n");
} else {
correct1 = true;
}
} while (correct1 == false);
num1 = num1input;
do {
printf("Please enter second number: ");
scanf("%s", num2input);
length = strlen(num2input);
for (i = 0; i < length; i++) {
if (!isdigit(num2input[i])) {
countErrors2++;
}
}
if (countErrors2 > 0) {
printf("Input is not a number \n");
} else {
correct2 = true;
}
} while (correct2 == false);
num2 = (int)num2input;
printf("%d %d \n", num1, num2);
int addition = num1 + num2;
int substraction = num1 - num2;
int multiplication = num1 * num2;
float division = num1 / num2;
printf("Addition: %d Subtraction: %d Multiplication: %d Division: %.1e", addition, substraction, multiplication, division);
getch();
}
You cannot convert a string to a number with a cast such as num1 = num1input;. You need to call a library function from <stdlib.h>:
#include <stdlib.h>
...
num1 = atoi(num1input);
But atoi ignores parsing errors. To ensure that overflows are detected, you can use strtol() as follows:
#include <errno.h>
#include <limits.h>
#include <stdlib.h>
...
errno = 0;
char *endp;
long lval = strtol(num1input, &endp, 10);
if (endp == num1input || errno != 0 || lval < INT_MIN || lval > INT_MAX) {
/* parse error detected:
* you could print an error message.
*/
if (lval < INT_MIN) lval = INT_MIN; /* clamp lval as an int value. */
if (lval > INT_MAX) lval = INT_MAX;
}
num1 = lval;
Or if you want to recognize hexadecimal syntax such as 0x10:
num1 = strtol(num1input, NULL, 0);
The same is applicable for num2input.
Note that isdigit(num1input[i]) is potentially incorrect if char is signed and num1input[i] has a negative value. You should write:
isdigit((unsigned char)num1input[i])
Also note that float division = num1 / num2; will compute the integer division and convert the result to a float. If you want the floating point division, you should write:
float division = (float)num1 / num2;
Note finally that it is recommended to use double instead of float for better accuracy.
Here is a corrected and simplified version:
#include <errno.h>
#include <limits.h>
#include <stdlib.h>
#include <stdio.h>
/* simple implementation of strtoi(), inspired by elegant code from chux */
int strtoi(const char *s, char **endptr, int base) {
long y = strtol(s, endptr, base);
#if INT_MAX != LONG_MAX
if (y > INT_MAX) {
errno = ERANGE;
return INT_MAX;
}
#endif
#if INT_MIN != LONG_MIN
if (y < INT_MIN) {
errno = ERANGE;
return INT_MIN;
}
#endif
return (int)y;
}
int main(void) {
char num1input[20];
char num2input[20];
char *endp;
int num1, num2;
for (;;) {
printf("Please enter a number: ");
if (scanf("%19s", num1input) != 1)
return 1;
errno = 0;
num1 = strtoi(num1input, &endp, 10);
if (errno == 0 && *endp == '\0')
break;
printf("Input is not a number\n");
}
for (;;) {
printf("Please enter a second number: ");
if (scanf("%19s", num2input) != 1)
return 1;
errno = 0;
num2 = strtoi(num2input, &endp, 10);
if (errno == 0 && *endp == '\0')
break;
printf("Input is not a number\n");
}
printf("%d %d\n", num1, num2);
int addition = num1 + num2;
int subtraction = num1 - num2;
int multiplication = num1 * num2;
double division = (double)num1 / num2;
printf("Addition: %d Subtraction: %d Multiplication: %d Division: %g\n",
addition, subtraction, multiplication, division);
getch();
}

Return a blank integer in c

I want to write a power function that prints "Unable to compute o^o" when asked to do so or return the integer result. how can I accomplish this?
My current code prints the error statement as well as the result statement.
My code:
#include <stdio.h>
double power(int base,int n);
int main() {
int no1,no2;
printf("Enter two numbers:\n");
printf("If you want to compute x^y enter x y\n");
scanf("%i%i", &no1, &no2);
printf("The value of %i^%i is %f", no1, no2, power(no1,no2));
return 0;
}
double power(int base, int n) {
double result = 1;
if( n == 0 && base == 0){
printf("Unable to compute 0^0\n");
}
else if( n == 0 && base != 0) {
result = 1;
}
else if( n>0 ){
for(n ; n>0 ; n--) {
result = result*base;
}
}
else if( n<0 ){
int temp = -n;
result = power(base,temp);
result = (float)1.0/result;
}
return result;
}
EDIT: I am actually a novice. I am in the first chapter of K&R where I found a power function. I wanted to improve that thing and found this hurdle. Hence please provide resources if possible so that I understand your answers.
#BartoszMarcinkowski gives you the correct answer, as an alternative (if you can't pass an extra variable) you can return NAN and check the result with isnan().
In computing, NaN, standing for not a number, is a numeric data type
value representing an undefined or unrepresentable value, especially
in floating-point calculations.
#include <stdio.h>
#include <math.h>
double power(int base,int n);
int main(void)
{
double f;
f = power(2, 2);
if (isnan(f)) {
printf("Unable to compute power\n");
} else {
printf("%f\n", f);
}
return 0;
}
double power(int base, int n) {
double result = 1;
if( n == 0 && base == 0){
return NAN;
}
...
return result;
}
It is common for C functions to return 0 on success or error code in case of failure.
#include <stdio.h>
int power(int base,int n, double *result);
int main() {
int no1, no2;
printf("Enter two numbers:\n");
printf("If you want to compute x^y enter x y\n");
scanf("%i%i", &no1, &no2);
double result;
int error = power(no1, no2, &result);
if(error == 0)
printf("The value of %i^%i is %f\n", no1, no2, result);
return 0;
}
int power(int base, int n, double *result) {
*result = 1;
if(n == 0 && base == 0){
printf("Unable to compute 0^0\n");
return 1;
} else if(n == 0 && base != 0) {
*result = 1;
return 0;
} else if(n>0){
for(; n>0 ; n--) {
*result = *result*base;
}
return 0;
} else if(n < 0){
int temp = -n;
power(base,temp, result);
*result = (float) 1.0 / *result;
return 0;
}
return 1;
}
Note : My answer is in reference to the user's post saying that he is
a novice at learning C, so I have assumed that he might not have yet
be comfortable dealing with pointers.
You can have an error flag in your code that tells the main function that an error has occurred.
You can use a global integer, that is common to all functions of your program to inform of errors in code.
After calling the power function, you check whether the error FLAG is set, which means errors have occurred. So you print the error message instead of the result.
What value you should use for showing a error has occurred is arbitrary. In most cases, a non-zero (sometimes negative) value can indicate the specific error. For example:
FLAG = -1 might indicate invalid input
FLAG = -2 might indicate invalid operation
And so on. etc. Here I have chosen FLAG = non-zero value to mean error has occurred.
#include <stdio.h>
double power(int base,int n);
--> char FLAG = 0;
int main() {
int no1,no2;
---- your code ---
double and = power(no1,no2);
--> if (char) {
printf("error : both values cannot be negative);
char = 0;
} else {
printf("The value of %i^%i is %f", no1, no2, ans);
}
return 0;
}
double power(int base, int n) {
---- your code ---
if( n == 0 && base == 0){
printf("Unable to compute 0^0\n");
--> FLAG = -1;
return 0;
}
else if( n == 0 && base != 0) {
result = 1;
}
else ---- your code ---
}

Pointer Division possible? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
How can i divide and multiplicate 2 variables in C with Pointers?
I tried this:
int multiplicate(int *x,int *y)
{
*x**y;
}
int divide(int *x,int *y)
{
*x/*y;
}
You are missing the return statement:
int multiplicate(int* x, int* y)
{
return (*x) * (*y);
}
int divide(int *x,int *y)
{
return (*x) / (*y);
}
Use *x/(*y) instead. Else it's interpreted as a multiline comment. And you forgot return
Since the indirection operator has higher precedence that multiplication operator, parenthesis are not needed.
Simply adding some whitespace will do:
int multiplicate(int *x,int *y)
{
return *x * *y;
}
int divide(int *x,int *y)
{
return *x / *y;
}
Pointer Division possible?
You do not try to devide pointers here, but as using the dereferencing *-operator, the values the pointers are pointing to are use.
However, as all examples given so far fully miss essential error checking, I propose the following approaches:
int multiply(int * pr, int * px, int * py)
{
int result = 0; /* Be optimistic. */
if (NULL == pr || NULL == px || NULL == py)
{
errno = EINVAL;
result = -1;
}
else
{
*pr = *px * *py;
}
return result;
}
int devide(int * pr, int * px, int * py)
{
int result = 0; /* Be optimistic. */
if (NULL == pr || NULL == px || NULL == py)
{
errno = EINVAL;
result = -1;
}
elseif (0 = *py) /* Division by zero is not defined. */
{
errno = EDOM;
result = -1;
}
else
{
*pr = *px / *py;
}
return result;
}
Call those functions like this:
#include <stdio.h>
#include <errno.h>
/* The two functions above go here. */
int main(int argc, char ** argv)
{
int result = EXIT_SUCCESS;
if (2 > argc)
{
fprintf("Missing or invalid arguments.\n");
printf("Usage: %s x y\n", argv[0]);
result = EXIT_FAILURE;
}
if (EXIT_SUCCESS == result)
{
int x = atoi(argv[1]); /* Better use strtol here. */
int y = atoi(argv[2]); /* Better use strtol here. */
printf("Got x = %d and y = %d.\n", x, y);
{
int r;
if (-1 == multiply(&r, &x, &y)
{
perror("multiply() failed");
}
else
{
printf("%d * %d = %d\n", x, y, r);
}
}
{
int r;
if (-1 == multiply(&r, &x, &y)
{
perror("devide() failed");
}
else
{
printf("%d / %d = %d\n", x, y, r);
}
}
}
return result;
}
Finally a more sane approach would be to use pointers only where needed.
A possible approch modifying the above examples would look like this:
int multiply(int * pr, int x, int y)
{
int result = 0; /* Be optimistic. */
if (NULL == pr)
{
errno = EINVAL;
result = -1;
}
else
{
*pr = x * y;
}
return result;
}
int devide(int * pr, int x, int y)
{
int result = 0; /* Be optimistic. */
if (NULL == pr)
{
errno = EINVAL;
result = -1;
}
elseif (0 = y) /* Division by zero is not defined. */
{
errno = EDOM;
result = -1;
}
else
{
*pr = x / y;
}
return result;
}
Call those functions like this:
#include <stdio.h>
#include <errno.h>
/* The two functions above go here. */
int main(int argc, char ** argv)
{
int result = EXIT_SUCCESS;
if (2 > argc)
{
fprintf("Missing or invalid arguments.\n");
printf("Usage: %s x y\n", argv[0]);
result = EXIT_FAILURE;
}
if (EXIT_SUCCESS == result)
{
int x = atoi(argv[1]); /* Better use strtol here. */
int y = atoi(argv[2]); /* Better use strtol here. */
printf("Got x = %d and y = %d.\n", x, y);
{
int r;
if (-1 == multiply(&r, x, y)
{
perror("multiply() failed");
}
else
{
printf("%d * %d = %d\n", x, y, r);
}
}
{
int r;
if (-1 == multiply(&r, x, y)
{
perror("devide() failed");
}
else
{
printf("%d / %d = %d\n", x, y, r);
}
}
}
return result;
}

Convert Ascii to Binary

I am writing a program where I need to convert Ascii characters to binary and then do a count. I have gotten my code working but it is printing additional information and not necessarily the correct binary. Below is my code as well as the output for a given set of characters. Any assistance would be greatly appreciated!
#include <stdio.h>
#include <stdlib.h>
void binaryPrinter(int digEnd, int value, int * noOfOnes);
void print(char c);
int charToInt(char c)
{
return (int) c;
}
int main()
{
char value;
int result = 1;
while(result != EOF)
{
result = scanf("%c", &value);
if(result != EOF)
{
print(value);
}
}
}
void binaryPrinter(int digEnd, int value, int * noOfOnes)
{
if(value & 1)
{
(*noOfOnes) = (*noOfOnes) + 1;
value = value >> 1;
digEnd--;
printf("1");
}
else
{
value = value >> 1;
digEnd--;
printf("0");
}
if(digEnd == 0)
return;
else
binaryPrinter(digEnd, value, noOfOnes);
}
void print(char c)
{
int count = 0;
printf("The character %c =", c);
binaryPrinter(8, charToInt(c), &count);
printf(" 1's = %d\n", count);
}
Here's a pair of functions:
void printCharAsBinary(char c) {
int i;
for(i = 0; i < 8; i++){
printf("%d", (c >> i) & 0x1);
}
}
void printStringAsBinary(char* s){
for(; *s; s++){
printCharAsBinary(*s);
printf(" ");
}
printf("\n");
}
You can see them in action here: http://ideone.com/3mEVbE. They work by masking out a single bit of each character and printing one at a time.

Resources