TaskI am new to C and I have small problem. I want to make program where I scan two numbers and get their sum: e.g. Input: 1 2 Output: 3
Input. 1.1 2.2 Output: 3.3
I struggle with switching between float or int. If I scan for int(%d) I can't get float variable, but if I scanf float then as 1st output I get 3.00 instead of 3. By this I want to achieve that decimal number will be in decimal form and number like 3 in its form without decimal zeros.
Thanks
CodePudding user response:
You can read the two numbers with std::cin
, then output the sum with std::cout
.
You can use std::fixed
and std::setprecision
to control the format of the output. Demo
#include <iomanip> // setprecision
#include <ios> // fixed
#include <iostream> // cin, cout
int main()
{
double d1{0.0};
double d2{0.0};
std::cin >> d1 >> d2;
std::cout << std::fixed << std::setprecision(5) << d1 << " " << d2 << " = " << d1 d2 << "\n";
}
If you want to output decimals only when needed, just don't use fixed
and precision
. Demo
#include <iostream> // cin, cout
int main()
{
double d1{0.0};
double d2{0.0};
std::cin >> d1 >> d2;
std::cout << d1 << " " << d2 << " = " << d1 d2 << "\n";
double d3{0.0};
double d4{0.0};
std::cin >> d3 >> d4;
std::cout << d3 << " " << d4 << " = " << d3 d4 << "\n";
}
CodePudding user response:
You can scan a std::string
, check whether there is a dot in it using std::find
and converting to an int (std::stoi
) or a float (std::stof
) accordingly. By the way, in C , you should use std::cin
instead of scanf
.