我制作了一个基于函数重载的程序,该程序由 2 个函数 int cube (int) 和 float cube(float) 组成。我的主要函数分别读取 int x 和 float y 的值。现在,当我运行程序时,我将浮点值而不是整数 va;ue 当我将 2.5(十进制值)而不是整数值放入变量“x”时,编译器不问我 y 的值,自动为 x (int) 取 2,为 y (float) 取 0.5,并返回 0.5 的立方。为什么会这样。为什么 0.5 会自动存储在 y 中而不是要求输入?
我的程序是这样的-
#include<iostream>
using namespace std;
int main()
{
int x;
float y;
int cube(int);
float cube(float);
cout<<"Enter a number to find its cube"<<endl;
cin>>x;
cout<<"The cube of the number "<<x<<" is "<<cube(x)<<endl;
cout<<"Enter a number to find its cube"<<endl;
cin>>y;
cout<<"The cube of the number "<<y<<" is "<<cube(y)<<endl;
return 0;
}
int cube (int num)
{
return num*num*num;
}
float cube (float num)
{
return num*num*num;
}
输出是 -
Enter a number to find its cube 2.5 The cube of number 2 is 8 Enter the number to find its cube The cube of number 0.5 is 0.125
谁能帮我解决这个问题 谢谢
最佳答案
您尝试读取一个 int
值,但给出了一个浮点值作为输入。这意味着程序将读取整数部分,一旦发现与整数值模式不匹配的内容(在您的情况下为 '.'
)就停止读取并将其留在下一次输入操作的输入缓冲区。
如果你想读取整行并丢弃未解析的输入,那么要么使用 std::istream::ignore
每次输入后。或者使用 std::getline
将整行读入字符串并使用 std::istringstream
“解析”输入。
关于c++ - 基于函数重载的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44217480/