我在 Cpp 中嘗試了一些東西,但是當我在用戶定義的函式
CODE 中使用相同的東西時沒有得到相同的輸出
#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?
uj5u.com熱心網友回復:
sum 的回傳值為 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
}
uj5u.com熱心網友回復:
表達方式
x / y
或者
a / b
具有浮動型別。在下面的陳述句中,沒有任何截斷的運算式的值被分配給浮點變數c。
c = a / b;
另一方面,這個呼叫的回傳值
sum(12, 5)
int由于函式的回傳型別而轉換為型別。因此可以截斷回傳值。
要獲得預期結果,請將函式的回傳型別更改為 float
float sum(int x, float y){
return (x / y);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/325450.html
