為了幫助我們理解 C 中的型別轉換,我們需要執行兩個int的加法,如下所示。如果我們分別提供兩個int和4,5輸出應該是4 5 = 9。
我試圖按照這個型別轉換教程沒有任何成功。有人可以給我一個提示或什么嗎?
逐字參考作業。
你的朋友寫了一個叫做加法器的程式。加法器應該接受用戶輸入的兩個數字,然后找到這些數字的總和,但它的行為很奇怪。
您的首要任務是找出加法器出了什么問題。你的第二個任務是修復它。
識別問題的提示
嘗試輸入 1 和 1。您希望輸出為 2,但您卻得到 11。同樣,如果您輸入 3 和 4,您希望輸出為 7,但您得到的是 34。請記住,字串連接也使用 運算子。識別解決方案
的提示 運算子的功能根據其前后的資料型別而有所不同。哪些資料型別會導致 運算子計算數學和?現在程式中存在什么資料型別?如何從一種資料型別轉換為另一種資料型別?查看 Type Casting 頁面了解一些想法
#include <iostream>
using namespace std;
int main() {
string num1;
string num2;
cout << "Type the first whole number and then press Enter or Return: ";
cin >> num1;
cout << "Type the second whole number and then press Enter or Return: ";
cin >> num2;
string sum = num1 num2;
cout << ( num1 " " num2 " = " sum ) << endl;
return 0;
}
uj5u.com熱心網友回復:
代碼的問題在于它在需要執行算術加法時執行字串連接。所以你需要把用戶的輸入變成數字變數,而不是字串。這項任務甚至暗示了這一點。
然而:
查看 Type Casting 頁面了解一些想法
這對這項任務來說是個壞建議,因為你無法解決型別轉換的問題。
您需要:
- 更改代碼以使用
int變數而不是string變數。這是首選的解決方案,例如:
#include <iostream>
using namespace std;
int main() {
int num1;
int num2;
cout << "Type the first whole number and then press Enter or Return: ";
cin >> num1;
cout << "Type the second whole number and then press Enter or Return: ";
cin >> num2;
int sum = num1 num2;
cout << num1 << " " << num2 << " = " << sum << endl;
return 0;
}
- 否則,如果你想繼續使用
string變數,你需要在運行時將它們的值轉換(不是型別轉換!)它們的值int,然后再轉換回來,例如:
#include <iostream>
#include <string>
using namespace std;
int main() {
string num1;
string num2;
cout << "Type the first whole number and then press Enter or Return: ";
cin >> num1;
cout << "Type the second whole number and then press Enter or Return: ";
cin >> num2;
int sum = stoi(num1) stoi(num2);
cout << ( num1 " " num2 " = " to_string(sum) ) << endl;
return 0;
}
uj5u.com熱心網友回復:
如果你對一個字符或字串進行型別轉換,它會被轉換成它的等效 ASCII 值,你需要使用 stoi 或從 '0' 中減去每個數字位置(有點重復作業)與 stoi 一起使用
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/412641.html
標籤:
