我正在開發一個程序來接受用戶對年齡變量的輸入,然後計算出該人應該進入的年級。我的代碼似乎正在運行,因爲它應該返回正確的值。然而;我也得到了兩個隨機整數以及這些值。我已經瀏覽過幾次,找不到問題。我的代碼如下所示,並且佈置在它是爲了滿足通過我的教授作爲此設置的可接受的程序的標準的方式被分配:在C++中返回隨機值的函數。找不到問題
#include <iostream>
using namespace std;
int gradecalculate (int age)
{
int grade;
if (age >= 6 && age <= 17)
grade= age-5;
return grade;
// Program does nothing if # not in range.
}
bool messagereturn (int age)
{
if (age < 5)
{cout << "You are too young for school." << endl;}
else if (age > 17)
{cout << "You are too old for school." << endl;}
else
{cout << "You should be in grade " << gradecalculate (age) << "." << endl;}
}
bool greet (int age)
{
if (age == 17)
{cout << "Hello Senior!" << endl;}
}
int main()
{
int age;
cout << "Enter your age: ";
cin >> age;
cout << messagereturn (age) << endl;
cout << greet (age) << endl;
return 0;
}
當運行該代碼(使用碼塊)的輸出爲如下,我無法接收任何錯誤代碼:
當進入17-
Enter your age: 17
You should be in grade 12.
96
Hello Senior!
96
當進入11 -
Enter your age: 11
You should be in grade 6.
96
11
'messagereturn'和'greet'被定義爲返回值,但沒有'return'語句。這構成了未定義的行爲。 – owacoder
'messagereturn()'和'greet()'都被聲明爲返回一個'bool'值,但它們都沒有返回任何東西。另外,由於'gradecalculate()'僅適用於5-17歲,所以不需要再次檢查年齡。在特定條件下編寫沒有返回值的函數是不好的。 –
我已經使用了隨機函數,它也給了我隨機的結果。 –