C++/Data Type/Float

Материал из C\C++ эксперт
Перейти к: навигация, поиск

10.0 would be interpreted as floating point

 
#include <iostream>
using namespace std;
int main(void)
{
   float firstOp = 10, result;
   int secondOp = 4;
   result = firstOp / secondOp;
   cout << firstOp << " / " << secondOp << " = " << result;
   return 0;
}


cin to read float in C++

 
#include <iostream>
using namespace std;
int main()
{
   double x, y;
   cout << "Enter two floating-point values: ";
   cin >> x ;
   cin >> y;
   cout << "The average of the two numbers is: " << (x + y)/2.0 << endl;
   return 0;
}


Demonstrates the definition and use of references.

 
#include <iostream>
#include <string>
using namespace std;
float x = 10.7F; 
int main()
{
   float  &rx = x; 
   rx *= 2;
   cout << "   x = " <<  x << endl    
        << "  rx = " << rx << endl;   
   const float& cref = x;    
   cout << "cref = " <<  cref << endl; 
   const string str = "I am a constant string!";

   const string& text = str;    
   cout << text << endl;        
   return 0;
}


Float value pointer and int value pointer

 
#include <iostream>
using namespace std;
int main()
{
  float *f;
  int *i;
  f = new float;
  i = new int;
  if(!f || !i) {
    cout << "Allocation error\n";
    return 1;
  }
  *f = 10.101;
  *i = 100;
  cout << *f << " " << *i << "\n";
  delete f;
  delete i;
  return 0;
}


Get the square and cube of a float type number

  
#include <iostream>
using namespace std;
float square_num(float num);
float cube_num(float num);
int main()
{
  int choice;
  float answer;
  answer = square_num(1.2);
  answer = cube_num(1.2);
  cout << "Your answer is " << answer <<" \n";
  return 0;
}
float square_num(float num)
{
   float a;
   a = num * num;
   return a;
}
 
float cube_num(float num)
{
  float a;
  a = num * num * num;
  return a;
}


Make the result of integer division a float

 

#include <iostream>
using namespace std;
int main(void)
{
   int firstOp = 10, secondOp = 4;
   float result = (float) firstOp / secondOp;
   cout << firstOp << " / " << secondOp << " = " << result;
   return 0;
}


Return float type from function

  
#include <iostream>
using namespace std;
float cube_number(float num);
float square_number(float num);
int main()
{
    float number;
    float number3;
    cout << "Please enter a number \n";
    cin >> number;
       
    if (number > 0 && number < 100)
    {
      number3 = cube_number(number);
      cout << number << "cubed is "<< number3;
    }else{
       number3 = square_number(number);
       cout << number << "squared is "<< number3;
    }
    
    if (number3 <10000 || number3 ==2){
       number3 = square_number(number3);
       cout << number3 << "squared is "<< number3;
    }
    return 0; 
}
float square_number(float num)
{
 float answer;
 answer = num * num;
 return answer;
}
float cube_number(float num)
{
 float answer;
 answer = num * num * num;
 return answer;
}