雷火电竞-中国电竞赛事及体育赛事平台

歡迎來到入門教程網(wǎng)!

C語(yǔ)言

當(dāng)前位置:主頁(yè) > 軟件編程 > C語(yǔ)言 >

C語(yǔ)言中交換int型變量的值及轉(zhuǎn)換為字符數(shù)組的方法

來源:本站原創(chuàng)|時(shí)間:2020-01-10|欄目:C語(yǔ)言|點(diǎn)擊:

不使用其他變量交換兩個(gè)整型的值:

#include <stdio.h> 
 
void main(){ 
  int a = 3; 
  int b = 4; 
 
  a = a ^ b;//使用異或交換 
  b = b ^ a; 
  a = a ^ b; 
 
  printf("%d, %d\n", a, b); 
 
  a = a - b;//使用加減交換 
  b = a + b; 
  a = b - a; 
 
  printf("%d, %d\n", a, b); 
 
  a ^= b ^= a ^= b; 
 
  printf("%d, %d\n", a, b); 
} 

整形和字符數(shù)組型轉(zhuǎn)換:

#include <stdio.h> 
#include <stdlib.h> 
 
int sumof1(int x)//求一個(gè)數(shù)轉(zhuǎn)換成二進(jìn)制以后1的個(gè)數(shù) 
{ 
  int countx = 0; 
  while(x) 
  { 
    countx ++; 
    x &= x-1; //每位與一次x - 1;就能消掉最后一個(gè)1 
  } 
  return countx; 
} 
 
void main(){ 
 
  char c[10]; 
  int i = 999; 
 
  itoa(i, c, 10);//以10進(jìn)制轉(zhuǎn)換成字符數(shù)組 
  puts(c); 
 
  itoa(i, c, 16);//以16進(jìn)制轉(zhuǎn)換成字符數(shù)組 
  printf("0x%s\n", c); 
 
  itoa(i, c, 8);//以8進(jìn)制轉(zhuǎn)換成字符數(shù)組 
  printf("0%s\n", c); 
 
  itoa(i, c, 2);//以2進(jìn)制轉(zhuǎn)換成字符數(shù)組 
  puts(c); 
 
  i = atoi(c);//再將字符串轉(zhuǎn)成整形 
  printf("%d\n", i); 
 
  printf("%d\n", sumof1(i));//以2進(jìn)制表示時(shí)1的個(gè)數(shù) 
} 

上一篇:C++計(jì)算每個(gè)字符出現(xiàn)的次數(shù)

欄    目:C語(yǔ)言

下一篇:C語(yǔ)言中用于產(chǎn)生隨機(jī)數(shù)的函數(shù)使用方法總結(jié)

本文標(biāo)題:C語(yǔ)言中交換int型變量的值及轉(zhuǎn)換為字符數(shù)組的方法

本文地址:http://m.jygsgssxh.com/a1/Cyuyan/2347.html

網(wǎng)頁(yè)制作CMS教程網(wǎng)絡(luò)編程軟件編程腳本語(yǔ)言數(shù)據(jù)庫(kù)服務(wù)器

如果侵犯了您的權(quán)利,請(qǐng)與我們聯(lián)系,我們將在24小時(shí)內(nèi)進(jìn)行處理、任何非本站因素導(dǎo)致的法律后果,本站均不負(fù)任何責(zé)任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有