[英]My code will only run the main function, other functions just wont compile in C++
我是C ++編程的初學者。 在我的課堂上,我們被證明使用函數和參數。 除了一個唯一的問題是我似乎無法開始之外,我們還剩下了應該使用函數的任務。 到目前為止,我已經編寫了兩個函數。 我的主要功能,要求用戶輸入。 另外一個使用此輸入來創建新整數的函數,稍后將需要。 我確定我的代碼中有幾個錯誤,但是現在我真的只需要知道為什么只有我的main函數才能執行。 我一直在尋找時間,並在其他地方進行切換,只是為了使除主程序以外的其他功能可以運行,但是我只會運行主功能,然后程序結束。 從用戶輸入數據后,程序將結束。 自從我開始這項任務以來,除了主要功能之外,我沒有其他任何功能可以運行。 我正在使用Visual Studio2017。很抱歉遇到麻煩。
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int digits(int zip);
int main() {
int zip = 0;
cout << "Enter zipcode: ";
cin >> zip;
return 0;
}
int digits(int zip){
int d5 = int();
d5 = zip % 10;
cout << "test: " << d5 << endl;
return d5;
}
您需要調用功能digits
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int digits(int zip);
int main() {
int zip = 0;
cout << "Enter zipcode: ";
cin >> zip;
int data = digits(zip);
cout<<"test: "<<data<<endl;
return 0;
}
int digits(int zip){
int d5 = int();
d5 = zip % 10;
// cout << "test: " << d5 << endl;
return d5;
}
C ++查找主函數並執行其中的任何內容。 在您的情況下,它將創建一個新的變量“ zip”,詢問用戶輸入,然后將該值插入zip變量。 然后返回0並停止運行。 您必須在int main()中調用函數digits()。 像這樣:
int main() {
int zip = 0;
cout << "Enter zipcode: ";
cin >> zip;
digits(zip);
return 0;
}
int digits(int zip){
int d5 = int();
d5 = zip % 10;
cout << "test: " << d5 << endl;
return d5;
}
此外,請注意,在執行digits()函數之后,該程序將僅返回0,而不以任何方式操縱“ d5”變量(由int digits()返回)。
同樣,在附加函數中引用任何內容也不是一個好主意。 這使得難以重用該功能。 為了使功能盡可能地通用,請確保它僅執行一項任務。 在您的情況下,它應如下所示:
int main() {
int zip = 0;
cout << "Enter zipcode: ";
cin >> zip;
cout << "test: " << digits(zip) << endl;
return 0;
}
int digits(int zip){
int d5 = int();
d5 = zip % 10;
return d5;
}
您需要事先調用函數digits
,否則程序將完全跳過該函數,因此上述代碼實際上應如下所示:
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int digits(int zip);
int main() {
int zip = 0;
cout << "Enter zipcode: ";
cin >> zip;
return 0;
}
int digits(int zip){
int d5 = int();
d5 = zip % 10;
cout << "test: " << d5 << endl;
return d5;
}
同樣在d5 = zip % 10;
旁注d5 = zip % 10;
如果您想更精確地將d5
定義為雙精度或浮點型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.