C 中兩個byte如何相加

2022-10-06 06:54:10 字數 700 閱讀 2599

發現問題

有人會想相加?還不簡單,用 + 呀。

byte a = 1;

byte b = 2;

byte c = a + b;

以上**是通不過編譯的,因為編譯器對待 + 時,有 www.cppcns.comint 相加、有 decimal 相加、有字串相加……就是沒有 byte 相加,所以它會用最接近的 int 相加,自然返回的結果也是 int,而 int 型別是不www.cppcns.com能直接賦值給更小的 byte 型別的。

解決方法

所以,得改成這樣:

byte a = 1;

byte b = 2;

byte c = (byte)(a + b);

還好+=不存在這個問題,a += b是沒問題的。

byte 最大值

byte 最小值是 0,最大值是 255,所以byte a = 256是通不過編譯的。

而 + 超過的就不一樣了。

byte a = 255;

a += 1; // 這裡結果是 0

byte b = 150;

b += 150; // 這裡結果是 44,若改為:b = (byte)(b + 150); 是一樣的。

www.cppcns.com總結

本文標題: c#中兩個byte如何相加

本文位址: /ruanjian/csharp/171537.html

合併兩個byte

byte sshead system.text.encoding.unicode.getbytes this is head byte sscontent system.text.encoding.unicode.getbytes this is content.sshead sscontent b...

兩個超大整數相加 c

昨天面試有個題,時間太緊,來不及寫了,回家除錯一下 函式原型 bool add const char a,const char b,char dest 思路 模擬人工加法的過程,先從末尾開始加。如果存在進製,則標記 include using namespace std bool add const...

C 兩個複數相加減

軟體技術2班 b16 完成日期2014年12月11日 double one,two,three,four console.writeline 請輸入第乙個複數實部的值 one convert.todouble console.readline console.writeline 請輸入第乙個複數虛部...