#include <iostream>
#include <string>
#include <algorithm>
using namespace std
void k_add(string a, string b, int k)
{
//将长的字符串放在前面
if (a.size() <b.size())
{
string temp = a
a = b
b = temp
}
//对源字符串进行翻转
reverse(a.begin(), a.end())
reverse(b.begin(), b.end())
bool carry = false//进位
//字符串相加
size_t i = 0
for (i <b.size()i++)
{
if (i <b.size())
{
a[i] += b[i] - '0'
if (carry) a[i] += 1
carry = false
if (a[i] >= k + '0')
{
a[i] -= k
carry = true
}
}
}
for (i <a.size()i++)
{
if (carry) a[i] += 1
carry = false
if (a[i] >= k + '0')
{
a[i] -= k
carry = true
}
}
if (carry)
{
a.push_back('1')
}
//输出
bool begin = false
for (int j = a.size() - 1j >= 0 j--)
{
if (a[j] >'0')
{
begin = true
}
if (begin)
{
cout <<a[j]
}
}
cout <<endl
}
简单模拟即可
3进制测试
10进制测试
getchar和putchar都是对字符操作的,而不是字符串,所以需要设计循环为字符串中每一个字符赋值。
以下是示例代码,需要说明的一点是gets输入字符串对于字符串长度没有限制,可能导致越界溢出,不安全,建议改用fgets,另外在新的微软标准中gets函数已被gets_s函数代替,希望对你有帮助。
include<stdio.h>intmain(){ const int count=21
charstr1[count]charstr2[count]charchprintf("请str1输入字符串(getchar方式):\n")int i=0while((ch=getchar())!'\n'){ str1[i]=chi+if(i=count-1){ str1[count-1]='\0'break} }
str1[i+]='\0'printf("下面输出str1(putchar方式):\n")int j=0while(str1[j]!'\0'){putchar(str1[j])j+}/printf
("请str1输入字符串(gets方式):\n")gets(str2)printf("下面输出str1(puts方式):\n")puts(str2)return0}
1.#include"stdio.hmain(){charcint letters=0,space=0,digit=0,others=0printf("pleaseinputsome characters\n")while((c=getchar())!'\n'){
if(c>='a'&c|c>='A'&c)
letters+else if(c=' ')space+else if(c>='0'&c)
digit+else
others+}printf("all in all:char=dspace=d digit=d others=d\n",letters,space,digit,others)}
2.#include"stdio.hmain()
{
int a,n,count=1long int sn=0,tn=0printf("pleaseinputa and n\n")scanf("%d,%d",&a,&n)printf("a=d,n=d\n",a,n)while(count)
{
tn=tn+asn=sn+tna=a*10count}printf("a+aa+.=ld\n",sn)}
3.#include"stdio.hmain()
{
int a[11]={1,4,6,9,13,16,19,28,40,100}inttemp1,temp2,number,end,i,jprintf("originalarrayis:\n")for(i=0ii+)printf("%5d",a[i])printf("\n")printf("inserta newnumber:")scanf("%d",&number)end=a[9]if(number>end)
a[10]=numberelse
{for(i=0ii+){ if(a[i]>number){temp1=a[i]a[i]=numberfor(j=i+1jj+){temp2=a[j]a[j]=temp1temp1=temp2}
break}
}
}
for(i=0ii+)printf("%6d",a[i])}