如果用户输入带十进制的数字,如何显示float;如果用户使用函数重载输入整数,则显示int [英] How to show float if the user inputs a digit with a decimal and int if the user inputs a whole number using function overloading

查看:162
本文介绍了如果用户输入带十进制的数字,如何显示float;如果用户使用函数重载输入整数,则显示int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在通过观看 bucky的C ++教程来学习C ++。

I am currently studying C++ by watching bucky's C++ tutorial.

在本教程中,他展示了如何使用函数重载
,但是变量值 a b 在他的教程视频中是固定的。
我想知道如果用户需要输入一些东西(十进制或整数)
,以及如何让程序识别输入数据是一个int还是一个浮点数会发生什么。

In the tutorial he shows how to use function overloading but the variables values of a and b are fixed in his tutorial video. I'm wondering what happens if the user needs to input something (decimal or whole number) and how to make the program identify whether the input data is an int or an float.

这里是教程视频中的代码:

here is the code in the tutorial video:

#include <iostream>
using namespace std;

void printnumber(int x){
    cout << "I am printing an integer " <<x << endl;
}

void printnumber(float x){
    cout << "I am printing an float: " << x << endl;
}


int main(){

    int a = 54;
    float b= 32.4896;

    printnumber(a);
    printnumber(b);

}

这里是我创建的代码:

#include <iostream>
using namespace std;
int a;
float b;

void printnumber(int x){
    cout << "I am printing an integer " <<x << endl;
}

void printnumber(float x){
    cout << "I am printing an float: " << x << endl;
}


int main(){

    cout << "enter a whole number or a number with decimal: ";
    cin >> ; //what will i put here?

    printnumber(a);
    printnumber(b);

}


推荐答案

不像一个人想的那样微不足道。一种方法是将输入读取为字符串,并查看该字符串是否包含小数点(这将导致语言环境中的问题,其中小数点是逗号)。

This is not as trivial as one would think. One way could be to read the input as a string, and see if the string contains a decimal-point (which would cause problems on locales where the decimal-point is a comma instead).

另一个解决方案是读为字符串,然后尝试将其转换浮点值,如果失败,则将其转换为整数

Another solution is to read as a string, then try to convert it to a floating point value, and if that fails then convert it to an integer.

我会推荐最后一种方法。

I would recommend the last method.

或者为了简单起见,只是指示用户输入一个整数,后跟一个浮点值:

Or for simplicity's sake, just instruct the user to input an integer followed by a floating point value:

int a;
std::cout << "Enter an integer value: ";
std::cin >> a;

float b;
std::cout << "Enter a floating point value: ";
std::cin >> b;

然后希望用户输入正确的值。

Then hope that the user actually enters correct values.

这篇关于如果用户输入带十进制的数字,如何显示float;如果用户使用函数重载输入整数,则显示int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆