php读取字符阿拉伯数字,php实现阿拉伯数字和罗马数字相互转换的方法

// Function that calculates the roman string to the given number:

function dec2roman($f)

{

// Return false if either $f is not a real number,

//$f is bigger than 3999 or $f is lower or equal to 0:

if(!is_numeric($f) || $f > 3999 || $f <= 0) return false;

// Define the roman figures:

$roman = array(

'M' => 1000,

'D' => 500,

'C' => 100,

'L' => 50,

'X' => 10,

'V' => 5,

'I' => 1

);

// Calculate the needed roman figures:

foreach($roman as $k => $v)

if(($amount[$k] = floor($f / $v)) > 0)

$f -= $amount[$k] * $v;

// Build the string:

$return = '';

foreach($amount as $k => $v)

{

$return .= $v <= 3 ? str_repeat($k, $v) : $k . $old_k;

$old_k = $k;

}

// Replace some spacial cases and return the string:

return str_replace(array('VIV','LXL','DCD'),array('IX','XC','CM'),$return);

}

// echo dec2romen(1981);

// Function to get the decimal value of a roman string:

function roman2dec($str = '')

{

// Return false if not at least one letter is in the string:

if(is_numeric($str)) return false;

// Define the roman figures:

$roman = array(

'M' => 1000,

'D' => 500,

'C' => 100,

'L' => 50,

'X' => 10,

'V' => 5,

'I' => 1

);

// Convert the string to an array of roman values:

for($i = 0; $i < strlen($str); $i++)

if(isset($roman[strtoupper($str[$i])]))

$values[] = $roman[strtoupper($str[$i])];

// Calculate the sum of that array:

$sum = 0;

while($current = current($values))

{

$next = next($values);

$next > $current ? $sum += $next - $current + 0 * next($values) : $sum += $current;

}

// Return the value:

return $sum;

}

// echo roman2dec(IX);

?>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的示例程序,可以实现字符串与数字之间的相互转换: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char str[20]; // 用于存储字符串的数组 int num; // 用于存储数字的变量 // 字符串转数字 printf("请输入一个数字:"); fgets(str, 20, stdin); // 从标准输入读取字符串 num = atoi(str); // 使用atoi函数将字符转换为整数 printf("转换后的数字为:%d\n", num); // 数字字符串 printf("请输入一个数字:"); scanf("%d", &num); // 从标准输入读取数字 sprintf(str, "%d", num); // 使用sprintf函数将数字转换字符串 printf("转换后的字符串为:%s\n", str); return 0; } ``` 在上面的程序中,我们使用了两个函数来完成字符串与数字转换: - atoi函数:将一个字符转换为整数。它的原型为`int atoi(const char *str)`,其中str为待转换字符串,返回值为转换后的整数。如果无法转换,则返回0。 - sprintf函数:将一个数字转换字符串。它的原型为`int sprintf(char *str, const char *format, ...)`,其中str为存储结果的字符串数组,format为格式化字符串,后面的省略号表示要输出的参数。该函数将format字符串中的格式标记替换为对应的参数值,并将结果保存在str中。函数返回值为输出的字符数。 需要注意的是,在使用fgets函数读取字符串时,我们指定了最大读取字符数为20,以避免数组溢出;而在使用scanf函数读取数字时,我们使用了`%d`格式标记,表示要读取一个整数。此外,为了方便输出结果,我们使用了printf函数来输出转换后的数字字符串。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值