没有通过用户定义的函数获得相同的输出
not getting same output via user defined function
我在 Cpp 中尝试了一些东西,但是当我在用户定义的函数中使用相同的东西时却没有得到相同的输出
代码
#include <iostream>
using namespace std;
int sum(int x, float y){
return (x / y);
}
int main(){
int a;
float b, c;
a = 12;
b = 5;
c = a / b;
cout << sum(12, 5) << endl;
cout << c;
}
输出
2
2.4
为什么我在这两种情况下都没有得到 2.4?
sum 的 return 值为 int。
#include <iostream>
using namespace std;
int sum(int x, float y){
return (x / y); //<< this is an int
}
int main(){
int a;
float b, c;
a = 12;
b = 5;
c = a / b; << this is a float
cout << sum(12, 5) << endl; //<< prints an int
cout << c; //<< prints a float
}
表达式
x / y
或
a / b
具有 float 类型。在下面的语句中,没有任何截断的表达式的值被分配给浮点变量 c
.
c = a / b;
另一方面,此调用的 returned 值
sum(12, 5)
由于函数的 return 类型, 被转换为 int
类型。因此可以截断 returned 值。
要获得预期结果,请将函数的 return 类型更改为 float
类型
float sum(int x, float y){
return (x / y);
}
我在 Cpp 中尝试了一些东西,但是当我在用户定义的函数中使用相同的东西时却没有得到相同的输出
代码
#include <iostream>
using namespace std;
int sum(int x, float y){
return (x / y);
}
int main(){
int a;
float b, c;
a = 12;
b = 5;
c = a / b;
cout << sum(12, 5) << endl;
cout << c;
}
输出
2
2.4
为什么我在这两种情况下都没有得到 2.4?
sum 的 return 值为 int。
#include <iostream>
using namespace std;
int sum(int x, float y){
return (x / y); //<< this is an int
}
int main(){
int a;
float b, c;
a = 12;
b = 5;
c = a / b; << this is a float
cout << sum(12, 5) << endl; //<< prints an int
cout << c; //<< prints a float
}
表达式
x / y
或
a / b
具有 float 类型。在下面的语句中,没有任何截断的表达式的值被分配给浮点变量 c
.
c = a / b;
另一方面,此调用的 returned 值
sum(12, 5)
由于函数的 return 类型, 被转换为 int
类型。因此可以截断 returned 值。
要获得预期结果,请将函数的 return 类型更改为 float
float sum(int x, float y){
return (x / y);
}