Zhejiang University Edition "C Language Programming (3rd Edition)" Topic Collection - Study Notes - Programming Questions - Exercise 2-10 Calculate piecewise function [1]

https://pintia.cn/problem-sets/12/problems/243

Exercise 2-10 Calculate the piecewise function [1] (10 points)
This problem asks to calculate the value of the following piecewise function f(x):

official

Input format:

Input gives the real number x in one line.

Output format:

Output in one line in the format "f(x) = result", where both x and result have one decimal place.

Input sample 1:

10

Sample output 1:

f(10.0) = 0.1

Input sample 2:

0

Sample output 2:

f(0.0) = 0.0

My initial code:

#include <stdio.h>

float f(float x)
{
  return (x!=0.0) ? (1.0/x) : (0.0);
}

int main()
{
  float x;
  if(scanf("%.1f", &x) == 1)
  {
    printf("f(%.1f) = %.1f", x, f(x));
  }

  return 0;
}

Error:

a.c: In functionmain’:
a.c:11:14: warning: unknown conversion type character ‘.’ in format [-Wformat=]
   if(scanf("%.1f", &x) == 1)
              ^
a.c:11:12: warning: too many arguments for format [-Wformat-extra-args]
   if(scanf("%.1f", &x) == 1)
            ^~~~~~

Probably understand, it should scanf("%.1f"be .1removed in . The modified code is:

#include <stdio.h>

float f(float x)
{
  return (x!=0.0) ? (1.0/x) : (0.0);
}

int main()
{
  float x;
  if(scanf("%f", &x) == 1)
  {
    printf("f(%.1f) = %.1f", x, f(x));
  }

  return 0;
}

References:
1. "C Language Programming (3rd Edition)" - Zhejiang University;
2. Zhejiang University Edition "C Language Programming (3rd Edition)" title collection .

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324688816&siteId=291194637